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 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
71 textElement.data('wlxmlNode').setText(toSet);
75 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
76 observer.observe(this.d[0], config);
79 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
80 var el = canvas.getDocumentElement(e.currentTarget);
84 if(el instanceof documentElement.DocumentTextElement)
88 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
89 var el = canvas.getDocumentElement(e.currentTarget);
93 if(el instanceof documentElement.DocumentTextElement)
95 el.toggleLabel(false);
98 this.eventBus.on('elementToggled', function(toggle, element) {
100 canvas.setCurrentElement(element.getPreviousTextElement());
112 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
115 toggleElementHighlight: function(node, toggle) {
116 var element = utils.findCanvasElement(node);
117 element.toggleHighlight(toggle);
120 createNodeElement: function(params) {
121 return documentElement.DocumentNodeElement.create(params, this);
124 wrapText: function(params) {
125 params = _.extend({textNodeIdx: 0}, params);
126 if(typeof params.textNodeIdx === 'number')
127 params.textNodeIdx = [params.textNodeIdx];
129 var childrenInside = params.inside.children(),
130 idx1 = Math.min.apply(Math, params.textNodeIdx),
131 idx2 = Math.max.apply(Math, params.textNodeIdx),
132 textNode1 = childrenInside[idx1],
133 textNode2 = childrenInside[idx2],
134 sameNode = textNode1.sameNode(textNode2),
135 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
136 prefixInside = textNode1.getText().substr(params.offsetStart),
137 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
138 suffixOutside = textNode2.getText().substr(params.offsetEnd)
141 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
142 textNode1.after(wrapperElement);
145 if(prefixOutside.length > 0)
146 wrapperElement.before({text:prefixOutside});
148 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
149 wrapperElement.append({text: core});
152 if(prefixInside.length > 0)
153 wrapperElement.append({text: prefixInside});
154 for(var i = idx1 + 1; i < idx2; i++) {
155 wrapperElement.append(childrenInside[i]);
157 if(suffixInside.length > 0)
158 wrapperElement.append({text: suffixInside});
160 if(suffixOutside.length > 0)
161 wrapperElement.after({text: suffixOutside});
162 return wrapperElement;
165 wrapElements: function(params) {
166 if(!(params.element1.parent().sameNode(params.element2.parent())))
169 var parent = params.element1.parent(),
170 parentChildren = parent.children(),
171 wrapper = this.createNodeElement({
172 tag: params._with.tag,
173 klass: params._with.klass}),
174 idx1 = parent.childIndex(params.element1),
175 idx2 = parent.childIndex(params.element2);
183 var insertingMethod, insertingTarget;
185 insertingMethod = 'prepend';
186 insertingTarget = parent;
188 insertingMethod = 'after';
189 insertingTarget = parentChildren[idx1-1];
192 for(var i = idx1; i <= idx2; i++) {
193 wrapper.append(parentChildren[i].detach());
196 insertingTarget[insertingMethod](wrapper);
200 getSiblingParents: function(params) {
201 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
202 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
203 noSiblingParents = null;
205 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
206 return noSiblingParents;
209 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
210 if(parents1[i].sameNode(parents2[i]))
214 return {element1: parents1[i], element2: parents2[i]};
217 getDocumentElement: function(from) {
218 if(from instanceof HTMLElement || from instanceof Text) {
219 return documentElement.DocumentElement.fromHTMLElement(from, this);
222 getCursor: function() {
223 return new Cursor(this);
229 getCurrentNodeElement: function() {
230 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
233 getCurrentTextElement: function() {
234 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
239 setCurrentElement: function(element, params) {
240 if(!(element instanceof documentElement.DocumentElement)) {
241 element = utils.findCanvasElement(element);
244 params = _.extend({caretTo: 'end'}, params);
245 var findFirstDirectTextChild = function(e, nodeToLand) {
246 var byBrowser = this.getCursor().getPosition().element;
247 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
249 var children = e.children();
250 for(var i = 0; i < children.length; i++) {
251 if(children[i] instanceof documentElement.DocumentTextElement)
256 var _markAsCurrent = function(element) {
257 if(element instanceof documentElement.DocumentTextElement) {
258 this.wrapper.find('.current-text-element').removeClass('current-text-element');
259 element.dom().addClass('current-text-element');
261 this.wrapper.find('.current-node-element').removeClass('current-node-element')
262 element._container().addClass('current-node-element');
263 this.publisher('currentElementChanged', element);
268 var isTextElement = element instanceof documentElement.DocumentTextElement,
269 nodeElementToLand = isTextElement ? element.parent() : element,
270 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
271 currentTextElement = this.getCurrentTextElement(),
272 currentNodeElement = this.getCurrentNodeElement();
274 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
275 this.wrapper.find('.current-text-element').removeClass('current-text-element');
277 if(textElementToLand) {
278 _markAsCurrent(textElementToLand);
279 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
280 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
281 if(!(textElementToLand.sameNode(currentTextElement)))
282 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
284 document.getSelection().removeAllRanges();
287 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
288 _markAsCurrent(nodeElementToLand);
290 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
294 _moveCaretToTextElement: function(element, where) {
295 var range = document.createRange(),
296 node = element.dom().contents()[0];
298 if(typeof where !== 'number') {
299 range.selectNodeContents(node);
301 range.setStart(node, where);
304 var collapseArg = true;
307 range.collapse(collapseArg);
309 var selection = document.getSelection();
311 selection.removeAllRanges();
312 selection.addRange(range);
313 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
316 setCursorPosition: function(position) {
318 this._moveCaretToTextElement(position.element, position.offset);
322 var parent = $('<div>'),
323 parts = this.doc().toXML(0);
324 parent.append(parts);
325 return parent.html();
329 $.extend(Canvas.prototype.list, {
330 create: function(params) {
331 if(!(params.element1.parent().sameNode(params.element2.parent())))
334 var parent = params.element1.parent(),
335 canvas = params.element1.canvas;
337 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
338 var tmp = params.element1;
339 params.element1 = params.element2;
340 params.element2 = tmp;
343 var elementsToWrap = [];
345 var place = 'before';
346 parent.children().some(function(element) {
348 if(element.sameNode(params.element1))
350 if(place === 'inside') {
351 if(element instanceof documentElement.DocumentTextElement) {
352 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
353 if(element.children()[0].sameNode(params.element1))
354 params.element1 = element;
356 element.setWlxmlClass('item');
357 elementsToWrap.push(element);
359 if(_e.sameNode(params.element2))
363 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
365 if(parent.is('list')) {
366 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
367 item.exec('toggleBullet', false);
368 toret = listElement.parent();
373 params.element1.before(toret);
375 elementsToWrap.forEach(function(element) {
377 listElement.append(element);
380 extractItems: function(params) {
381 params = _.extend({merge: true}, params);
382 var list = params.element1.parent();
383 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
386 var idx1 = list.childIndex(params.element1),
387 idx2 = list.childIndex(params.element2),
390 succeedingItems = [],
391 items = list.children(),
392 listIsNested = list.parent().getWlxmlClass() === 'item',
393 canvas = params.element1.canvas,
397 var tmp = idx1; idx1 = idx2; idx2 = tmp;
400 items.forEach(function(item, idx) {
402 precedingItems.push(item);
403 else if(idx >= idx1 && idx <= idx2) {
404 extractedItems.push(item);
407 succeedingItems.push(item);
411 var reference = listIsNested ? list.parent() : list;
412 if(succeedingItems.length === 0) {
413 var reference_orig = reference;
414 extractedItems.forEach(function(item) {
415 reference.after(item);
418 item.setWlxmlClass(null);
420 if(precedingItems.length === 0)
421 reference_orig.detach();
422 } else if(precedingItems.length === 0) {
423 extractedItems.forEach(function(item) {
424 reference.before(item);
426 item.setWlxmlClass(null);
429 extractedItems.forEach(function(item) {
430 reference.after(item);
432 item.setWlxmlClass(null);
435 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
439 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
441 succeedingItems.forEach(function(item) {
442 secondList.append(item);
445 reference.after(toAdd);
447 if(!params.merge && listIsNested) {
448 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
452 areItemsOfTheSameList: function(params) {
453 var e1 = params.element1,
454 e2 = params.element2;
455 return e1.parent().sameNode(e2.parent())
456 && e1.parent().is('list');
461 var Cursor = function(canvas) {
462 this.canvas = canvas;
465 $.extend(Cursor.prototype, {
466 isSelecting: function() {
467 var selection = window.getSelection();
468 return !selection.isCollapsed;
470 isSelectingWithinElement: function() {
471 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
473 isSelectingSiblings: function() {
474 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
476 getPosition: function() {
477 return this.getSelectionAnchor();
479 getSelectionStart: function() {
480 return this.getSelectionBoundry('start');
482 getSelectionEnd: function() {
483 return this.getSelectionBoundry('end');
485 getSelectionAnchor: function() {
486 return this.getSelectionBoundry('anchor');
488 getSelectionFocus: function() {
489 return this.getSelectionBoundry('focus');
491 getSelectionBoundry: function(which) {
492 var selection = window.getSelection(),
493 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
494 focusElement = this.canvas.getDocumentElement(selection.focusNode);
496 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
499 if(which === 'anchor') {
501 element: anchorElement,
502 offset: selection.anchorOffset,
503 offsetAtBeginning: selection.anchorOffset === 0,
504 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
507 if(which === 'focus') {
509 element: focusElement,
510 offset: selection.focusOffset,
511 offsetAtBeginning: selection.focusOffset === 0,
512 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
519 if(anchorElement.parent().sameNode(focusElement.parent())) {
520 var parent = anchorElement.parent(),
521 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
523 if(which === 'start') {
524 element = anchorElement;
525 offset = selection.anchorOffset
527 else if(which === 'end') {
528 element = focusElement,
529 offset = selection.focusOffset
532 if(which === 'start') {
533 element = focusElement,
534 offset = selection.focusOffset
536 else if(which === 'end') {
537 element = anchorElement;
538 offset = selection.anchorOffset
542 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
543 if(which === 'start') {
544 element = anchorElement;
545 offset = selection.anchorOffset
547 element = focusElement;
548 offset = selection.focusOffset
552 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
556 offsetAtBeginning: offset === 0,
557 offsetAtEnd: nodeLen === offset
563 fromXMLDocument: function(wlxmlDocument, publisher) {
564 return new Canvas(wlxmlDocument, publisher);