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 TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null};
14 $.extend(TextHandler.prototype, {
15 handle: function(node, text) {
16 console.log('canvas text handler: ' + text);
17 this.setText(text, node);
22 if(this.node.sameNode(node)) {
30 _ping: _.throttle(function(text) {
35 if(this.buffer != null) {
36 this.setText(this.buffer, this.node);
40 setText: function(text, node) {
41 this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
48 var Canvas = function(wlxmlDocument, publisher) {
49 this.eventBus = _.extend({}, Backbone.Events);
50 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
51 this.wlxmlListener = wlxmlListener.create(this);
52 this.loadWlxmlDocument(wlxmlDocument);
53 this.publisher = publisher ? publisher : function() {};
54 this.textHandler = new TextHandler(this);
57 $.extend(Canvas.prototype, {
59 loadWlxmlDocument: function(wlxmlDocument) {
64 this.wlxmlListener.listenTo(wlxmlDocument);
65 this.wlxmlDocument = wlxmlDocument;
67 this.setupEventHandling();
70 reloadRoot: function() {
71 var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
72 //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
75 this.wrapper.append(canvasDOM);
76 this.d = this.wrapper.children(0);
79 generateCanvasDOM: function(wlxmlNode) {
80 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
84 setupEventHandling: function() {
86 this.wrapper.on('keyup keydown keypress', function(e) {
87 keyboard.handleKey(e, this);
90 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
92 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
97 var observer = new MutationObserver(function(mutations) {
98 mutations.forEach(function(mutation) {
99 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
100 observer.disconnect();
101 if(mutation.target.data === '')
102 mutation.target.data = utils.unicode.ZWS;
103 else if(mutation.oldValue === utils.unicode.ZWS) {
104 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
105 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
107 observer.observe(canvas.d[0], config);
108 canvas.publisher('contentChanged');
110 var textElement = canvas.getDocumentElement(mutation.target),
111 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
113 //textElement.data('wlxmlNode').setText(toSet);
114 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
115 if(textElement.data('wlxmlNode').getText() != toSet) {
116 canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
121 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
122 observer.observe(this.d[0], config);
125 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
126 var el = canvas.getDocumentElement(e.currentTarget);
130 if(el instanceof documentElement.DocumentTextElement)
132 el.toggleLabel(true);
134 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
135 var el = canvas.getDocumentElement(e.currentTarget);
139 if(el instanceof documentElement.DocumentTextElement)
141 el.toggleLabel(false);
144 this.eventBus.on('elementToggled', function(toggle, element) {
146 canvas.setCurrentElement(element.getPreviousTextElement());
158 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
161 toggleElementHighlight: function(node, toggle) {
162 var element = utils.findCanvasElement(node);
163 element.toggleHighlight(toggle);
166 createNodeElement: function(params) {
167 return documentElement.DocumentNodeElement.create(params, this);
170 getDocumentElement: function(from) {
171 if(from instanceof HTMLElement || from instanceof Text) {
172 return documentElement.DocumentElement.fromHTMLElement(from, this);
175 getCursor: function() {
176 return new Cursor(this);
182 getCurrentNodeElement: function() {
183 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
186 getCurrentTextElement: function() {
187 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
192 setCurrentElement: function(element, params) {
193 if(!(element instanceof documentElement.DocumentElement)) {
194 element = utils.findCanvasElement(element);
197 params = _.extend({caretTo: 'end'}, params);
198 var findFirstDirectTextChild = function(e, nodeToLand) {
199 var byBrowser = this.getCursor().getPosition().element;
200 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
202 var children = e.children();
203 for(var i = 0; i < children.length; i++) {
204 if(children[i] instanceof documentElement.DocumentTextElement)
209 var _markAsCurrent = function(element) {
210 if(element instanceof documentElement.DocumentTextElement) {
211 this.wrapper.find('.current-text-element').removeClass('current-text-element');
212 element.dom().addClass('current-text-element');
214 this.wrapper.find('.current-node-element').removeClass('current-node-element')
215 element._container().addClass('current-node-element');
216 this.publisher('currentElementChanged', element);
221 var isTextElement = element instanceof documentElement.DocumentTextElement,
222 nodeElementToLand = isTextElement ? element.parent() : element,
223 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
224 currentTextElement = this.getCurrentTextElement(),
225 currentNodeElement = this.getCurrentNodeElement();
227 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
228 this.wrapper.find('.current-text-element').removeClass('current-text-element');
230 if(textElementToLand) {
231 _markAsCurrent(textElementToLand);
232 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
233 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
234 if(!(textElementToLand.sameNode(currentTextElement)))
235 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
237 document.getSelection().removeAllRanges();
240 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
241 _markAsCurrent(nodeElementToLand);
243 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
247 _moveCaretToTextElement: function(element, where) {
248 var range = document.createRange(),
249 node = element.dom().contents()[0];
251 if(typeof where !== 'number') {
252 range.selectNodeContents(node);
254 range.setStart(node, where);
257 var collapseArg = true;
260 range.collapse(collapseArg);
262 var selection = document.getSelection();
264 selection.removeAllRanges();
265 selection.addRange(range);
266 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
269 setCursorPosition: function(position) {
271 this._moveCaretToTextElement(position.element, position.offset);
275 $.extend(Canvas.prototype.list, {
276 create: function(params) {
277 if(!(params.element1.parent().sameNode(params.element2.parent())))
280 var parent = params.element1.parent(),
281 canvas = params.element1.canvas;
283 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
284 var tmp = params.element1;
285 params.element1 = params.element2;
286 params.element2 = tmp;
289 var elementsToWrap = [];
291 var place = 'before';
292 parent.children().some(function(element) {
294 if(element.sameNode(params.element1))
296 if(place === 'inside') {
297 if(element instanceof documentElement.DocumentTextElement) {
298 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
299 if(element.children()[0].sameNode(params.element1))
300 params.element1 = element;
302 element.setWlxmlClass('item');
303 elementsToWrap.push(element);
305 if(_e.sameNode(params.element2))
309 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
311 if(parent.is('list')) {
312 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
313 item.exec('toggleBullet', false);
314 toret = listElement.parent();
319 params.element1.before(toret);
321 elementsToWrap.forEach(function(element) {
323 listElement.append(element);
326 extractItems: function(params) {
327 params = _.extend({merge: true}, params);
328 var list = params.element1.parent();
329 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
332 var idx1 = list.childIndex(params.element1),
333 idx2 = list.childIndex(params.element2),
336 succeedingItems = [],
337 items = list.children(),
338 listIsNested = list.parent().getWlxmlClass() === 'item',
339 canvas = params.element1.canvas,
343 var tmp = idx1; idx1 = idx2; idx2 = tmp;
346 items.forEach(function(item, idx) {
348 precedingItems.push(item);
349 else if(idx >= idx1 && idx <= idx2) {
350 extractedItems.push(item);
353 succeedingItems.push(item);
357 var reference = listIsNested ? list.parent() : list;
358 if(succeedingItems.length === 0) {
359 var reference_orig = reference;
360 extractedItems.forEach(function(item) {
361 reference.after(item);
364 item.setWlxmlClass(null);
366 if(precedingItems.length === 0)
367 reference_orig.detach();
368 } else if(precedingItems.length === 0) {
369 extractedItems.forEach(function(item) {
370 reference.before(item);
372 item.setWlxmlClass(null);
375 extractedItems.forEach(function(item) {
376 reference.after(item);
378 item.setWlxmlClass(null);
381 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
385 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
387 succeedingItems.forEach(function(item) {
388 secondList.append(item);
391 reference.after(toAdd);
393 if(!params.merge && listIsNested) {
394 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
398 areItemsOfTheSameList: function(params) {
399 var e1 = params.element1,
400 e2 = params.element2;
401 return e1.parent().sameNode(e2.parent())
402 && e1.parent().is('list');
407 var Cursor = function(canvas) {
408 this.canvas = canvas;
411 $.extend(Cursor.prototype, {
412 isSelecting: function() {
413 var selection = window.getSelection();
414 return !selection.isCollapsed;
416 isSelectingWithinElement: function() {
417 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
419 isSelectingSiblings: function() {
420 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
422 getPosition: function() {
423 return this.getSelectionAnchor();
425 getSelectionStart: function() {
426 return this.getSelectionBoundry('start');
428 getSelectionEnd: function() {
429 return this.getSelectionBoundry('end');
431 getSelectionAnchor: function() {
432 return this.getSelectionBoundry('anchor');
434 getSelectionFocus: function() {
435 return this.getSelectionBoundry('focus');
437 getSelectionBoundry: function(which) {
438 var selection = window.getSelection(),
439 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
440 focusElement = this.canvas.getDocumentElement(selection.focusNode);
442 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
445 if(which === 'anchor') {
447 element: anchorElement,
448 offset: selection.anchorOffset,
449 offsetAtBeginning: selection.anchorOffset === 0,
450 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
453 if(which === 'focus') {
455 element: focusElement,
456 offset: selection.focusOffset,
457 offsetAtBeginning: selection.focusOffset === 0,
458 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
465 if(anchorElement.parent().sameNode(focusElement.parent())) {
466 var parent = anchorElement.parent(),
467 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
469 if(which === 'start') {
470 element = anchorElement;
471 offset = selection.anchorOffset
473 else if(which === 'end') {
474 element = focusElement,
475 offset = selection.focusOffset
478 if(which === 'start') {
479 element = focusElement,
480 offset = selection.focusOffset
482 else if(which === 'end') {
483 element = anchorElement;
484 offset = selection.anchorOffset
488 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
489 if(which === 'start') {
490 element = anchorElement;
491 offset = selection.anchorOffset
493 element = focusElement;
494 offset = selection.focusOffset
498 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
502 offsetAtBeginning: offset === 0,
503 offsetAtEnd: nodeLen === offset
509 fromXMLDocument: function(wlxmlDocument, publisher) {
510 return new Canvas(wlxmlDocument, publisher);