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 createNodeElement: function(params) {
114 return documentElement.DocumentNodeElement.create(params, this);
117 wrapText: function(params) {
118 params = _.extend({textNodeIdx: 0}, params);
119 if(typeof params.textNodeIdx === 'number')
120 params.textNodeIdx = [params.textNodeIdx];
122 var childrenInside = params.inside.children(),
123 idx1 = Math.min.apply(Math, params.textNodeIdx),
124 idx2 = Math.max.apply(Math, params.textNodeIdx),
125 textNode1 = childrenInside[idx1],
126 textNode2 = childrenInside[idx2],
127 sameNode = textNode1.sameNode(textNode2),
128 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
129 prefixInside = textNode1.getText().substr(params.offsetStart),
130 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
131 suffixOutside = textNode2.getText().substr(params.offsetEnd)
134 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
135 textNode1.after(wrapperElement);
138 if(prefixOutside.length > 0)
139 wrapperElement.before({text:prefixOutside});
141 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
142 wrapperElement.append({text: core});
145 if(prefixInside.length > 0)
146 wrapperElement.append({text: prefixInside});
147 for(var i = idx1 + 1; i < idx2; i++) {
148 wrapperElement.append(childrenInside[i]);
150 if(suffixInside.length > 0)
151 wrapperElement.append({text: suffixInside});
153 if(suffixOutside.length > 0)
154 wrapperElement.after({text: suffixOutside});
155 return wrapperElement;
158 wrapElements: function(params) {
159 if(!(params.element1.parent().sameNode(params.element2.parent())))
162 var parent = params.element1.parent(),
163 parentChildren = parent.children(),
164 wrapper = this.createNodeElement({
165 tag: params._with.tag,
166 klass: params._with.klass}),
167 idx1 = parent.childIndex(params.element1),
168 idx2 = parent.childIndex(params.element2);
176 var insertingMethod, insertingTarget;
178 insertingMethod = 'prepend';
179 insertingTarget = parent;
181 insertingMethod = 'after';
182 insertingTarget = parentChildren[idx1-1];
185 for(var i = idx1; i <= idx2; i++) {
186 wrapper.append(parentChildren[i].detach());
189 insertingTarget[insertingMethod](wrapper);
193 getSiblingParents: function(params) {
194 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
195 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
196 noSiblingParents = null;
198 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
199 return noSiblingParents;
202 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
203 if(parents1[i].sameNode(parents2[i]))
207 return {element1: parents1[i], element2: parents2[i]};
210 getDocumentElement: function(from) {
211 if(from instanceof HTMLElement || from instanceof Text) {
212 return documentElement.DocumentElement.fromHTMLElement(from, this);
215 getCursor: function() {
216 return new Cursor(this);
222 getCurrentNodeElement: function() {
223 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
226 getCurrentTextElement: function() {
227 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
232 setCurrentElement: function(element, params) {
233 params = _.extend({caretTo: 'end'}, params);
234 var findFirstDirectTextChild = function(e, nodeToLand) {
235 var byBrowser = this.getCursor().getPosition().element;
236 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
238 var children = e.children();
239 for(var i = 0; i < children.length; i++) {
240 if(children[i] instanceof documentElement.DocumentTextElement)
245 var _markAsCurrent = function(element) {
246 if(element instanceof documentElement.DocumentTextElement) {
247 this.wrapper.find('.current-text-element').removeClass('current-text-element');
248 element.dom().addClass('current-text-element');
250 this.wrapper.find('.current-node-element').removeClass('current-node-element')
251 element._container().addClass('current-node-element');
252 this.publisher('currentElementChanged', element);
257 var isTextElement = element instanceof documentElement.DocumentTextElement,
258 nodeElementToLand = isTextElement ? element.parent() : element,
259 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
260 currentTextElement = this.getCurrentTextElement(),
261 currentNodeElement = this.getCurrentNodeElement();
263 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
264 this.wrapper.find('.current-text-element').removeClass('current-text-element');
266 if(textElementToLand) {
267 _markAsCurrent(textElementToLand);
268 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
269 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
270 if(!(textElementToLand.sameNode(currentTextElement)))
271 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
273 document.getSelection().removeAllRanges();
276 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
277 _markAsCurrent(nodeElementToLand);
279 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
283 _moveCaretToTextElement: function(element, where) {
284 var range = document.createRange(),
285 node = element.dom().contents()[0];
287 if(typeof where !== 'number') {
288 range.selectNodeContents(node);
290 range.setStart(node, where);
293 var collapseArg = true;
296 range.collapse(collapseArg);
298 var selection = document.getSelection();
300 selection.removeAllRanges();
301 selection.addRange(range);
302 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
305 setCursorPosition: function(position) {
307 this._moveCaretToTextElement(position.element, position.offset);
311 var parent = $('<div>'),
312 parts = this.doc().toXML(0);
313 parent.append(parts);
314 return parent.html();
318 $.extend(Canvas.prototype.list, {
319 create: function(params) {
320 if(!(params.element1.parent().sameNode(params.element2.parent())))
323 var parent = params.element1.parent(),
324 canvas = params.element1.canvas;
326 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
327 var tmp = params.element1;
328 params.element1 = params.element2;
329 params.element2 = tmp;
332 var elementsToWrap = [];
334 var place = 'before';
335 parent.children().some(function(element) {
337 if(element.sameNode(params.element1))
339 if(place === 'inside') {
340 if(element instanceof documentElement.DocumentTextElement) {
341 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
342 if(element.children()[0].sameNode(params.element1))
343 params.element1 = element;
345 element.setWlxmlClass('item');
346 elementsToWrap.push(element);
348 if(_e.sameNode(params.element2))
352 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
354 if(parent.is('list')) {
355 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
356 item.exec('toggleBullet', false);
357 toret = listElement.parent();
362 params.element1.before(toret);
364 elementsToWrap.forEach(function(element) {
366 listElement.append(element);
369 extractItems: function(params) {
370 params = _.extend({merge: true}, params);
371 var list = params.element1.parent();
372 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
375 var idx1 = list.childIndex(params.element1),
376 idx2 = list.childIndex(params.element2),
379 succeedingItems = [],
380 items = list.children(),
381 listIsNested = list.parent().getWlxmlClass() === 'item',
382 canvas = params.element1.canvas,
386 var tmp = idx1; idx1 = idx2; idx2 = tmp;
389 items.forEach(function(item, idx) {
391 precedingItems.push(item);
392 else if(idx >= idx1 && idx <= idx2) {
393 extractedItems.push(item);
396 succeedingItems.push(item);
400 var reference = listIsNested ? list.parent() : list;
401 if(succeedingItems.length === 0) {
402 var reference_orig = reference;
403 extractedItems.forEach(function(item) {
404 reference.after(item);
407 item.setWlxmlClass(null);
409 if(precedingItems.length === 0)
410 reference_orig.detach();
411 } else if(precedingItems.length === 0) {
412 extractedItems.forEach(function(item) {
413 reference.before(item);
415 item.setWlxmlClass(null);
418 extractedItems.forEach(function(item) {
419 reference.after(item);
421 item.setWlxmlClass(null);
424 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
428 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
430 succeedingItems.forEach(function(item) {
431 secondList.append(item);
434 reference.after(toAdd);
436 if(!params.merge && listIsNested) {
437 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
441 areItemsOfTheSameList: function(params) {
442 var e1 = params.element1,
443 e2 = params.element2;
444 return e1.parent().sameNode(e2.parent())
445 && e1.parent().is('list');
450 var Cursor = function(canvas) {
451 this.canvas = canvas;
454 $.extend(Cursor.prototype, {
455 isSelecting: function() {
456 var selection = window.getSelection();
457 return !selection.isCollapsed;
459 isSelectingWithinElement: function() {
460 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
462 isSelectingSiblings: function() {
463 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
465 getPosition: function() {
466 return this.getSelectionAnchor();
468 getSelectionStart: function() {
469 return this.getSelectionBoundry('start');
471 getSelectionEnd: function() {
472 return this.getSelectionBoundry('end');
474 getSelectionAnchor: function() {
475 return this.getSelectionBoundry('anchor');
477 getSelectionFocus: function() {
478 return this.getSelectionBoundry('focus');
480 getSelectionBoundry: function(which) {
481 var selection = window.getSelection(),
482 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
483 focusElement = this.canvas.getDocumentElement(selection.focusNode);
485 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
488 if(which === 'anchor') {
490 element: anchorElement,
491 offset: selection.anchorOffset,
492 offsetAtBeginning: selection.anchorOffset === 0,
493 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
496 if(which === 'focus') {
498 element: focusElement,
499 offset: selection.focusOffset,
500 offsetAtBeginning: selection.focusOffset === 0,
501 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
508 if(anchorElement.parent().sameNode(focusElement.parent())) {
509 var parent = anchorElement.parent(),
510 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
512 if(which === 'start') {
513 element = anchorElement;
514 offset = selection.anchorOffset
516 else if(which === 'end') {
517 element = focusElement,
518 offset = selection.focusOffset
521 if(which === 'start') {
522 element = focusElement,
523 offset = selection.focusOffset
525 else if(which === 'end') {
526 element = anchorElement;
527 offset = selection.anchorOffset
531 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
532 if(which === 'start') {
533 element = anchorElement;
534 offset = selection.anchorOffset
536 element = focusElement;
537 offset = selection.focusOffset
541 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
545 offsetAtBeginning: offset === 0,
546 offsetAtEnd: nodeLen === offset
552 fromXMLDocument: function(wlxmlDocument, publisher) {
553 return new Canvas(wlxmlDocument, publisher);