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.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
15 this.loadWlxmlDocument(wlxmlDocument);
16 this.publisher = publisher ? publisher : function() {};
19 $.extend(Canvas.prototype, {
21 loadWlxmlDocument: function(wlxmlDocument) {
25 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
28 this.wrapper.append(canvasDOM);
29 this.d = this.wrapper.children(0);
30 this.setupEventHandling();
33 generateCanvasDOM: function(wlxmlNode) {
34 // var element = this.createNodeElement2({
35 // tag: wlxmlNode.getTagName(),
36 // klass: wlxmlNode.getClass(), //currentTag.attr('class'),
37 // meta: wlxmlNode.getMetaAttributes(), //meta,
38 // others: wlxmlNode.getOtherAttributes(), // ~ //others,
39 // rawChildren: wlxmlNode.contents(),
40 // prepopulateOnEmpty: true
43 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
46 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
47 element.data(attr, '');
52 setupEventHandling: function() {
54 this.wrapper.on('keyup keydown keypress', function(e) {
55 keyboard.handleKey(e, this);
58 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
60 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
63 var observer = new MutationObserver(function(mutations) {
64 mutations.forEach(function(mutation) {
65 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
66 observer.disconnect();
67 if(mutation.target.data === '')
68 mutation.target.data = utils.unicode.ZWS;
69 else if(mutation.oldValue === utils.unicode.ZWS) {
70 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
71 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
73 observer.observe(canvas.d[0], config);
74 canvas.publisher('contentChanged');
78 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
79 observer.observe(this.d[0], config);
82 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
83 var el = canvas.getDocumentElement(e.currentTarget);
87 if(el instanceof documentElement.DocumentTextElement)
91 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
92 var el = canvas.getDocumentElement(e.currentTarget);
96 if(el instanceof documentElement.DocumentTextElement)
98 el.toggleLabel(false);
101 this.eventBus.on('elementToggled', function(toggle, element) {
103 canvas.setCurrentElement(element.getPreviousTextElement());
115 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
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 params = _.extend({caretTo: 'end'}, params);
239 var findFirstDirectTextChild = function(e, nodeToLand) {
240 var byBrowser = this.getCursor().getPosition().element;
241 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
243 var children = e.children();
244 for(var i = 0; i < children.length; i++) {
245 if(children[i] instanceof documentElement.DocumentTextElement)
250 var _markAsCurrent = function(element) {
251 if(element instanceof documentElement.DocumentTextElement) {
252 this.wrapper.find('.current-text-element').removeClass('current-text-element');
253 element.dom().addClass('current-text-element');
255 this.wrapper.find('.current-node-element').removeClass('current-node-element')
256 element._container().addClass('current-node-element');
257 this.publisher('currentElementChanged', element);
262 var isTextElement = element instanceof documentElement.DocumentTextElement,
263 nodeElementToLand = isTextElement ? element.parent() : element,
264 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
265 currentTextElement = this.getCurrentTextElement(),
266 currentNodeElement = this.getCurrentNodeElement();
268 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
269 this.wrapper.find('.current-text-element').removeClass('current-text-element');
271 if(textElementToLand) {
272 _markAsCurrent(textElementToLand);
273 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
274 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
275 if(!(textElementToLand.sameNode(currentTextElement)))
276 this.publisher('currentTextElementSet', textElementToLand);
278 document.getSelection().removeAllRanges();
281 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
282 _markAsCurrent(nodeElementToLand);
284 this.publisher('currentNodeElementSet', nodeElementToLand);
288 _moveCaretToTextElement: function(element, where) {
289 var range = document.createRange(),
290 node = element.dom().contents()[0];
292 if(typeof where !== 'number') {
293 range.selectNodeContents(node);
295 range.setStart(node, where);
298 var collapseArg = true;
301 range.collapse(collapseArg);
303 var selection = document.getSelection();
305 selection.removeAllRanges();
306 selection.addRange(range);
307 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
310 setCursorPosition: function(position) {
312 this._moveCaretToTextElement(position.element, position.offset);
316 var parent = $('<div>'),
317 parts = this.doc().toXML(0);
318 parent.append(parts);
319 return parent.html();
323 $.extend(Canvas.prototype.list, {
324 create: function(params) {
325 if(!(params.element1.parent().sameNode(params.element2.parent())))
328 var parent = params.element1.parent(),
329 canvas = params.element1.canvas;
331 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
332 var tmp = params.element1;
333 params.element1 = params.element2;
334 params.element2 = tmp;
337 var elementsToWrap = [];
339 var place = 'before';
340 parent.children().some(function(element) {
342 if(element.sameNode(params.element1))
344 if(place === 'inside') {
345 if(element instanceof documentElement.DocumentTextElement) {
346 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
347 if(element.children()[0].sameNode(params.element1))
348 params.element1 = element;
350 element.setWlxmlClass('item');
351 elementsToWrap.push(element);
353 if(_e.sameNode(params.element2))
357 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
359 if(parent.is('list')) {
360 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
361 item.exec('toggleBullet', false);
362 toret = listElement.parent();
367 params.element1.before(toret);
369 elementsToWrap.forEach(function(element) {
371 listElement.append(element);
374 extractItems: function(params) {
375 params = _.extend({merge: true}, params);
376 var list = params.element1.parent();
377 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
380 var idx1 = list.childIndex(params.element1),
381 idx2 = list.childIndex(params.element2),
384 succeedingItems = [],
385 items = list.children(),
386 listIsNested = list.parent().getWlxmlClass() === 'item',
387 canvas = params.element1.canvas,
391 var tmp = idx1; idx1 = idx2; idx2 = tmp;
394 items.forEach(function(item, idx) {
396 precedingItems.push(item);
397 else if(idx >= idx1 && idx <= idx2) {
398 extractedItems.push(item);
401 succeedingItems.push(item);
405 var reference = listIsNested ? list.parent() : list;
406 if(succeedingItems.length === 0) {
407 var reference_orig = reference;
408 extractedItems.forEach(function(item) {
409 reference.after(item);
412 item.setWlxmlClass(null);
414 if(precedingItems.length === 0)
415 reference_orig.detach();
416 } else if(precedingItems.length === 0) {
417 extractedItems.forEach(function(item) {
418 reference.before(item);
420 item.setWlxmlClass(null);
423 extractedItems.forEach(function(item) {
424 reference.after(item);
426 item.setWlxmlClass(null);
429 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
433 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
435 succeedingItems.forEach(function(item) {
436 secondList.append(item);
439 reference.after(toAdd);
441 if(!params.merge && listIsNested) {
442 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
446 areItemsOfTheSameList: function(params) {
447 var e1 = params.element1,
448 e2 = params.element2;
449 return e1.parent().sameNode(e2.parent())
450 && e1.parent().is('list');
455 var Cursor = function(canvas) {
456 this.canvas = canvas;
459 $.extend(Cursor.prototype, {
460 isSelecting: function() {
461 var selection = window.getSelection();
462 return !selection.isCollapsed;
464 isSelectingWithinElement: function() {
465 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
467 isSelectingSiblings: function() {
468 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
470 getPosition: function() {
471 return this.getSelectionAnchor();
473 getSelectionStart: function() {
474 return this.getSelectionBoundry('start');
476 getSelectionEnd: function() {
477 return this.getSelectionBoundry('end');
479 getSelectionAnchor: function() {
480 return this.getSelectionBoundry('anchor');
482 getSelectionFocus: function() {
483 return this.getSelectionBoundry('focus');
485 getSelectionBoundry: function(which) {
486 var selection = window.getSelection(),
487 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
488 focusElement = this.canvas.getDocumentElement(selection.focusNode);
490 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
493 if(which === 'anchor') {
495 element: anchorElement,
496 offset: selection.anchorOffset,
497 offsetAtBeginning: selection.anchorOffset === 0,
498 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
501 if(which === 'focus') {
503 element: focusElement,
504 offset: selection.focusOffset,
505 offsetAtBeginning: selection.focusOffset === 0,
506 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
513 if(anchorElement.parent().sameNode(focusElement.parent())) {
514 var parent = anchorElement.parent(),
515 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
517 if(which === 'start') {
518 element = anchorElement;
519 offset = selection.anchorOffset
521 else if(which === 'end') {
522 element = focusElement,
523 offset = selection.focusOffset
526 if(which === 'start') {
527 element = focusElement,
528 offset = selection.focusOffset
530 else if(which === 'end') {
531 element = anchorElement;
532 offset = selection.anchorOffset
536 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
537 if(which === 'start') {
538 element = anchorElement;
539 offset = selection.anchorOffset
541 element = focusElement;
542 offset = selection.focusOffset
546 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
550 offsetAtBeginning: offset === 0,
551 offsetAtEnd: nodeLen === offset
557 fromXMLDocument: function(wlxmlDocument, publisher) {
558 return new Canvas(wlxmlDocument, publisher);