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.loadWlxmlDocument(wlxmlDocument);
15 this.publisher = publisher ? publisher : function() {};
18 $.extend(Canvas.prototype, {
20 loadWlxmlDocument: function(wlxmlDocument) {
24 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
26 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
27 this.wrapper.append(canvasDOM);
28 this.d = this.wrapper.children(0);
29 this.setupEventHandling();
32 generateCanvasDOM: function(wlxmlNode) {
33 // var element = this.createNodeElement2({
34 // tag: wlxmlNode.getTagName(),
35 // klass: wlxmlNode.getClass(), //currentTag.attr('class'),
36 // meta: wlxmlNode.getMetaAttributes(), //meta,
37 // others: wlxmlNode.getOtherAttributes(), // ~ //others,
38 // rawChildren: wlxmlNode.contents(),
39 // prepopulateOnEmpty: true
42 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
45 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
46 element.data(attr, '');
51 setupEventHandling: function() {
53 this.wrapper.on('keyup keydown keypress', function(e) {
54 keyboard.handleKey(e, this);
57 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
59 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
62 var observer = new MutationObserver(function(mutations) {
63 mutations.forEach(function(mutation) {
64 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
65 observer.disconnect();
66 if(mutation.target.data === '')
67 mutation.target.data = utils.unicode.ZWS;
68 else if(mutation.oldValue === utils.unicode.ZWS) {
69 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
70 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
72 observer.observe(canvas.d[0], config);
73 canvas.publisher('contentChanged');
77 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
78 observer.observe(this.d[0], config);
81 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
82 var el = canvas.getDocumentElement(e.currentTarget);
86 if(el instanceof documentElement.DocumentTextElement)
90 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
91 var el = canvas.getDocumentElement(e.currentTarget);
95 if(el instanceof documentElement.DocumentTextElement)
97 el.toggleLabel(false);
100 this.eventBus.on('elementToggled', function(toggle, element) {
102 canvas.setCurrentElement(element.getPreviousTextElement());
114 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
117 createNodeElement: function(params) {
118 return documentElement.DocumentNodeElement.create(params, this);
121 wrapText: function(params) {
122 params = _.extend({textNodeIdx: 0}, params);
123 if(typeof params.textNodeIdx === 'number')
124 params.textNodeIdx = [params.textNodeIdx];
126 var childrenInside = params.inside.children(),
127 idx1 = Math.min.apply(Math, params.textNodeIdx),
128 idx2 = Math.max.apply(Math, params.textNodeIdx),
129 textNode1 = childrenInside[idx1],
130 textNode2 = childrenInside[idx2],
131 sameNode = textNode1.sameNode(textNode2),
132 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
133 prefixInside = textNode1.getText().substr(params.offsetStart),
134 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
135 suffixOutside = textNode2.getText().substr(params.offsetEnd)
138 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
139 textNode1.after(wrapperElement);
142 if(prefixOutside.length > 0)
143 wrapperElement.before({text:prefixOutside});
145 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
146 wrapperElement.append({text: core});
149 if(prefixInside.length > 0)
150 wrapperElement.append({text: prefixInside});
151 for(var i = idx1 + 1; i < idx2; i++) {
152 wrapperElement.append(childrenInside[i]);
154 if(suffixInside.length > 0)
155 wrapperElement.append({text: suffixInside});
157 if(suffixOutside.length > 0)
158 wrapperElement.after({text: suffixOutside});
159 return wrapperElement;
162 wrapElements: function(params) {
163 if(!(params.element1.parent().sameNode(params.element2.parent())))
166 var parent = params.element1.parent(),
167 parentChildren = parent.children(),
168 wrapper = this.createNodeElement({
169 tag: params._with.tag,
170 klass: params._with.klass}),
171 idx1 = parent.childIndex(params.element1),
172 idx2 = parent.childIndex(params.element2);
180 var insertingMethod, insertingTarget;
182 insertingMethod = 'prepend';
183 insertingTarget = parent;
185 insertingMethod = 'after';
186 insertingTarget = parentChildren[idx1-1];
189 for(var i = idx1; i <= idx2; i++) {
190 wrapper.append(parentChildren[i].detach());
193 insertingTarget[insertingMethod](wrapper);
197 getSiblingParents: function(params) {
198 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
199 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
200 noSiblingParents = null;
202 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
203 return noSiblingParents;
206 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
207 if(parents1[i].sameNode(parents2[i]))
211 return {element1: parents1[i], element2: parents2[i]};
214 getDocumentElement: function(from) {
215 if(from instanceof HTMLElement || from instanceof Text) {
216 return documentElement.DocumentElement.fromHTMLElement(from, this);
219 getCursor: function() {
220 return new Cursor(this);
226 getCurrentNodeElement: function() {
227 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
230 getCurrentTextElement: function() {
231 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
236 setCurrentElement: function(element, params) {
237 params = _.extend({caretTo: 'end'}, params);
238 var findFirstDirectTextChild = function(e, nodeToLand) {
239 var byBrowser = this.getCursor().getPosition().element;
240 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
242 var children = e.children();
243 for(var i = 0; i < children.length; i++) {
244 if(children[i] instanceof documentElement.DocumentTextElement)
249 var _markAsCurrent = function(element) {
250 if(element instanceof documentElement.DocumentTextElement) {
251 this.wrapper.find('.current-text-element').removeClass('current-text-element');
252 element.dom().addClass('current-text-element');
254 this.wrapper.find('.current-node-element').removeClass('current-node-element')
255 element._container().addClass('current-node-element');
256 this.publisher('currentElementChanged', element);
261 var isTextElement = element instanceof documentElement.DocumentTextElement,
262 nodeElementToLand = isTextElement ? element.parent() : element,
263 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
264 currentTextElement = this.getCurrentTextElement(),
265 currentNodeElement = this.getCurrentNodeElement();
267 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
268 this.wrapper.find('.current-text-element').removeClass('current-text-element');
270 if(textElementToLand) {
271 _markAsCurrent(textElementToLand);
272 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
273 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
274 if(!(textElementToLand.sameNode(currentTextElement)))
275 this.publisher('currentTextElementSet', textElementToLand);
277 document.getSelection().removeAllRanges();
280 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
281 _markAsCurrent(nodeElementToLand);
283 this.publisher('currentNodeElementSet', nodeElementToLand);
287 _moveCaretToTextElement: function(element, where) {
288 var range = document.createRange(),
289 node = element.dom().contents()[0];
291 if(typeof where !== 'number') {
292 range.selectNodeContents(node);
294 range.setStart(node, where);
297 var collapseArg = true;
300 range.collapse(collapseArg);
302 var selection = document.getSelection();
304 selection.removeAllRanges();
305 selection.addRange(range);
306 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
309 setCursorPosition: function(position) {
311 this._moveCaretToTextElement(position.element, position.offset);
315 var parent = $('<div>'),
316 parts = this.doc().toXML(0);
317 parent.append(parts);
318 return parent.html();
322 $.extend(Canvas.prototype.list, {
323 create: function(params) {
324 if(!(params.element1.parent().sameNode(params.element2.parent())))
327 var parent = params.element1.parent(),
328 canvas = params.element1.canvas;
330 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
331 var tmp = params.element1;
332 params.element1 = params.element2;
333 params.element2 = tmp;
336 var elementsToWrap = [];
338 var place = 'before';
339 parent.children().some(function(element) {
341 if(element.sameNode(params.element1))
343 if(place === 'inside') {
344 if(element instanceof documentElement.DocumentTextElement) {
345 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
346 if(element.children()[0].sameNode(params.element1))
347 params.element1 = element;
349 element.setWlxmlClass('item');
350 elementsToWrap.push(element);
352 if(_e.sameNode(params.element2))
356 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
358 if(parent.is('list')) {
359 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
360 item.exec('toggleBullet', false);
361 toret = listElement.parent();
366 params.element1.before(toret);
368 elementsToWrap.forEach(function(element) {
370 listElement.append(element);
373 extractItems: function(params) {
374 params = _.extend({merge: true}, params);
375 var list = params.element1.parent();
376 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
379 var idx1 = list.childIndex(params.element1),
380 idx2 = list.childIndex(params.element2),
383 succeedingItems = [],
384 items = list.children(),
385 listIsNested = list.parent().getWlxmlClass() === 'item',
386 canvas = params.element1.canvas,
390 var tmp = idx1; idx1 = idx2; idx2 = tmp;
393 items.forEach(function(item, idx) {
395 precedingItems.push(item);
396 else if(idx >= idx1 && idx <= idx2) {
397 extractedItems.push(item);
400 succeedingItems.push(item);
404 var reference = listIsNested ? list.parent() : list;
405 if(succeedingItems.length === 0) {
406 var reference_orig = reference;
407 extractedItems.forEach(function(item) {
408 reference.after(item);
411 item.setWlxmlClass(null);
413 if(precedingItems.length === 0)
414 reference_orig.detach();
415 } else if(precedingItems.length === 0) {
416 extractedItems.forEach(function(item) {
417 reference.before(item);
419 item.setWlxmlClass(null);
422 extractedItems.forEach(function(item) {
423 reference.after(item);
425 item.setWlxmlClass(null);
428 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
432 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
434 succeedingItems.forEach(function(item) {
435 secondList.append(item);
438 reference.after(toAdd);
440 if(!params.merge && listIsNested) {
441 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
445 areItemsOfTheSameList: function(params) {
446 var e1 = params.element1,
447 e2 = params.element2;
448 return e1.parent().sameNode(e2.parent())
449 && e1.parent().is('list');
454 var Cursor = function(canvas) {
455 this.canvas = canvas;
458 $.extend(Cursor.prototype, {
459 isSelecting: function() {
460 var selection = window.getSelection();
461 return !selection.isCollapsed;
463 isSelectingWithinElement: function() {
464 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
466 isSelectingSiblings: function() {
467 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
469 getPosition: function() {
470 return this.getSelectionAnchor();
472 getSelectionStart: function() {
473 return this.getSelectionBoundry('start');
475 getSelectionEnd: function() {
476 return this.getSelectionBoundry('end');
478 getSelectionAnchor: function() {
479 return this.getSelectionBoundry('anchor');
481 getSelectionFocus: function() {
482 return this.getSelectionBoundry('focus');
484 getSelectionBoundry: function(which) {
485 var selection = window.getSelection(),
486 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
487 focusElement = this.canvas.getDocumentElement(selection.focusNode);
489 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
492 if(which === 'anchor') {
494 element: anchorElement,
495 offset: selection.anchorOffset,
496 offsetAtBeginning: selection.anchorOffset === 0,
497 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
500 if(which === 'focus') {
502 element: focusElement,
503 offset: selection.focusOffset,
504 offsetAtBeginning: selection.focusOffset === 0,
505 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
512 if(anchorElement.parent().sameNode(focusElement.parent())) {
513 var parent = anchorElement.parent(),
514 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
516 if(which === 'start') {
517 element = anchorElement;
518 offset = selection.anchorOffset
520 else if(which === 'end') {
521 element = focusElement,
522 offset = selection.focusOffset
525 if(which === 'start') {
526 element = focusElement,
527 offset = selection.focusOffset
529 else if(which === 'end') {
530 element = anchorElement;
531 offset = selection.anchorOffset
535 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
536 if(which === 'start') {
537 element = anchorElement;
538 offset = selection.anchorOffset
540 element = focusElement;
541 offset = selection.focusOffset
545 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
549 offsetAtBeginning: offset === 0,
550 offsetAtEnd: nodeLen === offset
556 fromXMLDocument: function(wlxmlDocument, publisher) {
557 return new Canvas(wlxmlDocument, publisher);