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.loadWlxmlDocument(wlxmlDocument);
17 this.publisher = publisher ? publisher : function() {};
18 this.wlxmlListener = wlxmlListener.create(this);
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);
38 generateCanvasDOM: function(wlxmlNode) {
39 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
43 setupEventHandling: function() {
45 this.wrapper.on('keyup keydown keypress', function(e) {
46 keyboard.handleKey(e, this);
49 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
51 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
54 var observer = new MutationObserver(function(mutations) {
55 mutations.forEach(function(mutation) {
56 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
57 observer.disconnect();
58 if(mutation.target.data === '')
59 mutation.target.data = utils.unicode.ZWS;
60 else if(mutation.oldValue === utils.unicode.ZWS) {
61 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
62 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
64 observer.observe(canvas.d[0], config);
65 canvas.publisher('contentChanged');
69 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
70 observer.observe(this.d[0], config);
73 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
74 var el = canvas.getDocumentElement(e.currentTarget);
78 if(el instanceof documentElement.DocumentTextElement)
82 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
83 var el = canvas.getDocumentElement(e.currentTarget);
87 if(el instanceof documentElement.DocumentTextElement)
89 el.toggleLabel(false);
92 this.eventBus.on('elementToggled', function(toggle, element) {
94 canvas.setCurrentElement(element.getPreviousTextElement());
106 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
109 createNodeElement: function(params) {
110 return documentElement.DocumentNodeElement.create(params, this);
113 wrapText: function(params) {
114 params = _.extend({textNodeIdx: 0}, params);
115 if(typeof params.textNodeIdx === 'number')
116 params.textNodeIdx = [params.textNodeIdx];
118 var childrenInside = params.inside.children(),
119 idx1 = Math.min.apply(Math, params.textNodeIdx),
120 idx2 = Math.max.apply(Math, params.textNodeIdx),
121 textNode1 = childrenInside[idx1],
122 textNode2 = childrenInside[idx2],
123 sameNode = textNode1.sameNode(textNode2),
124 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
125 prefixInside = textNode1.getText().substr(params.offsetStart),
126 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
127 suffixOutside = textNode2.getText().substr(params.offsetEnd)
130 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
131 textNode1.after(wrapperElement);
134 if(prefixOutside.length > 0)
135 wrapperElement.before({text:prefixOutside});
137 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
138 wrapperElement.append({text: core});
141 if(prefixInside.length > 0)
142 wrapperElement.append({text: prefixInside});
143 for(var i = idx1 + 1; i < idx2; i++) {
144 wrapperElement.append(childrenInside[i]);
146 if(suffixInside.length > 0)
147 wrapperElement.append({text: suffixInside});
149 if(suffixOutside.length > 0)
150 wrapperElement.after({text: suffixOutside});
151 return wrapperElement;
154 wrapElements: function(params) {
155 if(!(params.element1.parent().sameNode(params.element2.parent())))
158 var parent = params.element1.parent(),
159 parentChildren = parent.children(),
160 wrapper = this.createNodeElement({
161 tag: params._with.tag,
162 klass: params._with.klass}),
163 idx1 = parent.childIndex(params.element1),
164 idx2 = parent.childIndex(params.element2);
172 var insertingMethod, insertingTarget;
174 insertingMethod = 'prepend';
175 insertingTarget = parent;
177 insertingMethod = 'after';
178 insertingTarget = parentChildren[idx1-1];
181 for(var i = idx1; i <= idx2; i++) {
182 wrapper.append(parentChildren[i].detach());
185 insertingTarget[insertingMethod](wrapper);
189 getSiblingParents: function(params) {
190 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
191 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
192 noSiblingParents = null;
194 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
195 return noSiblingParents;
198 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
199 if(parents1[i].sameNode(parents2[i]))
203 return {element1: parents1[i], element2: parents2[i]};
206 getDocumentElement: function(from) {
207 if(from instanceof HTMLElement || from instanceof Text) {
208 return documentElement.DocumentElement.fromHTMLElement(from, this);
211 getCursor: function() {
212 return new Cursor(this);
218 getCurrentNodeElement: function() {
219 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
222 getCurrentTextElement: function() {
223 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
228 setCurrentElement: function(element, params) {
229 params = _.extend({caretTo: 'end'}, params);
230 var findFirstDirectTextChild = function(e, nodeToLand) {
231 var byBrowser = this.getCursor().getPosition().element;
232 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
234 var children = e.children();
235 for(var i = 0; i < children.length; i++) {
236 if(children[i] instanceof documentElement.DocumentTextElement)
241 var _markAsCurrent = function(element) {
242 if(element instanceof documentElement.DocumentTextElement) {
243 this.wrapper.find('.current-text-element').removeClass('current-text-element');
244 element.dom().addClass('current-text-element');
246 this.wrapper.find('.current-node-element').removeClass('current-node-element')
247 element._container().addClass('current-node-element');
248 this.publisher('currentElementChanged', element);
253 var isTextElement = element instanceof documentElement.DocumentTextElement,
254 nodeElementToLand = isTextElement ? element.parent() : element,
255 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
256 currentTextElement = this.getCurrentTextElement(),
257 currentNodeElement = this.getCurrentNodeElement();
259 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
260 this.wrapper.find('.current-text-element').removeClass('current-text-element');
262 if(textElementToLand) {
263 _markAsCurrent(textElementToLand);
264 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
265 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
266 if(!(textElementToLand.sameNode(currentTextElement)))
267 this.publisher('currentTextElementSet', textElementToLand);
269 document.getSelection().removeAllRanges();
272 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
273 _markAsCurrent(nodeElementToLand);
275 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
279 _moveCaretToTextElement: function(element, where) {
280 var range = document.createRange(),
281 node = element.dom().contents()[0];
283 if(typeof where !== 'number') {
284 range.selectNodeContents(node);
286 range.setStart(node, where);
289 var collapseArg = true;
292 range.collapse(collapseArg);
294 var selection = document.getSelection();
296 selection.removeAllRanges();
297 selection.addRange(range);
298 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
301 setCursorPosition: function(position) {
303 this._moveCaretToTextElement(position.element, position.offset);
307 var parent = $('<div>'),
308 parts = this.doc().toXML(0);
309 parent.append(parts);
310 return parent.html();
314 $.extend(Canvas.prototype.list, {
315 create: function(params) {
316 if(!(params.element1.parent().sameNode(params.element2.parent())))
319 var parent = params.element1.parent(),
320 canvas = params.element1.canvas;
322 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
323 var tmp = params.element1;
324 params.element1 = params.element2;
325 params.element2 = tmp;
328 var elementsToWrap = [];
330 var place = 'before';
331 parent.children().some(function(element) {
333 if(element.sameNode(params.element1))
335 if(place === 'inside') {
336 if(element instanceof documentElement.DocumentTextElement) {
337 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
338 if(element.children()[0].sameNode(params.element1))
339 params.element1 = element;
341 element.setWlxmlClass('item');
342 elementsToWrap.push(element);
344 if(_e.sameNode(params.element2))
348 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
350 if(parent.is('list')) {
351 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
352 item.exec('toggleBullet', false);
353 toret = listElement.parent();
358 params.element1.before(toret);
360 elementsToWrap.forEach(function(element) {
362 listElement.append(element);
365 extractItems: function(params) {
366 params = _.extend({merge: true}, params);
367 var list = params.element1.parent();
368 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
371 var idx1 = list.childIndex(params.element1),
372 idx2 = list.childIndex(params.element2),
375 succeedingItems = [],
376 items = list.children(),
377 listIsNested = list.parent().getWlxmlClass() === 'item',
378 canvas = params.element1.canvas,
382 var tmp = idx1; idx1 = idx2; idx2 = tmp;
385 items.forEach(function(item, idx) {
387 precedingItems.push(item);
388 else if(idx >= idx1 && idx <= idx2) {
389 extractedItems.push(item);
392 succeedingItems.push(item);
396 var reference = listIsNested ? list.parent() : list;
397 if(succeedingItems.length === 0) {
398 var reference_orig = reference;
399 extractedItems.forEach(function(item) {
400 reference.after(item);
403 item.setWlxmlClass(null);
405 if(precedingItems.length === 0)
406 reference_orig.detach();
407 } else if(precedingItems.length === 0) {
408 extractedItems.forEach(function(item) {
409 reference.before(item);
411 item.setWlxmlClass(null);
414 extractedItems.forEach(function(item) {
415 reference.after(item);
417 item.setWlxmlClass(null);
420 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
424 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
426 succeedingItems.forEach(function(item) {
427 secondList.append(item);
430 reference.after(toAdd);
432 if(!params.merge && listIsNested) {
433 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
437 areItemsOfTheSameList: function(params) {
438 var e1 = params.element1,
439 e2 = params.element2;
440 return e1.parent().sameNode(e2.parent())
441 && e1.parent().is('list');
446 var Cursor = function(canvas) {
447 this.canvas = canvas;
450 $.extend(Cursor.prototype, {
451 isSelecting: function() {
452 var selection = window.getSelection();
453 return !selection.isCollapsed;
455 isSelectingWithinElement: function() {
456 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
458 isSelectingSiblings: function() {
459 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
461 getPosition: function() {
462 return this.getSelectionAnchor();
464 getSelectionStart: function() {
465 return this.getSelectionBoundry('start');
467 getSelectionEnd: function() {
468 return this.getSelectionBoundry('end');
470 getSelectionAnchor: function() {
471 return this.getSelectionBoundry('anchor');
473 getSelectionFocus: function() {
474 return this.getSelectionBoundry('focus');
476 getSelectionBoundry: function(which) {
477 var selection = window.getSelection(),
478 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
479 focusElement = this.canvas.getDocumentElement(selection.focusNode);
481 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
484 if(which === 'anchor') {
486 element: anchorElement,
487 offset: selection.anchorOffset,
488 offsetAtBeginning: selection.anchorOffset === 0,
489 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
492 if(which === 'focus') {
494 element: focusElement,
495 offset: selection.focusOffset,
496 offsetAtBeginning: selection.focusOffset === 0,
497 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
504 if(anchorElement.parent().sameNode(focusElement.parent())) {
505 var parent = anchorElement.parent(),
506 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
508 if(which === 'start') {
509 element = anchorElement;
510 offset = selection.anchorOffset
512 else if(which === 'end') {
513 element = focusElement,
514 offset = selection.focusOffset
517 if(which === 'start') {
518 element = focusElement,
519 offset = selection.focusOffset
521 else if(which === 'end') {
522 element = anchorElement;
523 offset = selection.anchorOffset
527 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
528 if(which === 'start') {
529 element = anchorElement;
530 offset = selection.anchorOffset
532 element = focusElement;
533 offset = selection.focusOffset
537 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
541 offsetAtBeginning: offset === 0,
542 offsetAtEnd: nodeLen === offset
548 fromXMLDocument: function(wlxmlDocument, publisher) {
549 return new Canvas(wlxmlDocument, publisher);