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});
42 node.transform('smartxml.setText', {text: text});
49 var Canvas = function(wlxmlDocument, publisher) {
50 this.eventBus = _.extend({}, Backbone.Events);
51 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
52 this.wlxmlListener = wlxmlListener.create(this);
53 this.loadWlxmlDocument(wlxmlDocument);
54 this.publisher = publisher ? publisher : function() {};
55 this.textHandler = new TextHandler(this);
58 $.extend(Canvas.prototype, {
60 loadWlxmlDocument: function(wlxmlDocument) {
65 this.wlxmlListener.listenTo(wlxmlDocument);
66 this.wlxmlDocument = wlxmlDocument;
68 this.setupEventHandling();
71 reloadRoot: function() {
72 var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
73 //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
76 this.wrapper.append(canvasDOM);
77 this.d = this.wrapper.children(0);
80 generateCanvasDOM: function(wlxmlNode) {
81 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
85 setupEventHandling: function() {
87 this.wrapper.on('keyup keydown keypress', function(e) {
88 keyboard.handleKey(e, this);
91 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
93 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
98 var observer = new MutationObserver(function(mutations) {
99 mutations.forEach(function(mutation) {
100 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
101 observer.disconnect();
102 if(mutation.target.data === '')
103 mutation.target.data = utils.unicode.ZWS;
104 else if(mutation.oldValue === utils.unicode.ZWS) {
105 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
106 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
108 observer.observe(canvas.wrapper[0], config);
109 canvas.publisher('contentChanged');
111 var textElement = canvas.getDocumentElement(mutation.target),
112 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
114 //textElement.data('wlxmlNode').setText(toSet);
115 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
116 if(textElement.data('wlxmlNode').getText() != toSet) {
117 canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
122 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
123 observer.observe(this.wrapper[0], config);
126 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
127 var el = canvas.getDocumentElement(e.currentTarget);
131 if(el instanceof documentElement.DocumentTextElement)
133 el.toggleLabel(true);
135 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
136 var el = canvas.getDocumentElement(e.currentTarget);
140 if(el instanceof documentElement.DocumentTextElement)
142 el.toggleLabel(false);
145 this.eventBus.on('elementToggled', function(toggle, element) {
147 canvas.setCurrentElement(element.getPreviousTextElement());
159 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
162 toggleElementHighlight: function(node, toggle) {
163 var element = utils.findCanvasElement(node);
164 element.toggleHighlight(toggle);
167 createNodeElement: function(params) {
168 return documentElement.DocumentNodeElement.create(params, this);
171 getDocumentElement: function(from) {
172 if(from instanceof HTMLElement || from instanceof Text) {
173 return documentElement.DocumentElement.fromHTMLElement(from, this);
176 getCursor: function() {
177 return new Cursor(this);
183 getCurrentNodeElement: function() {
184 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
187 getCurrentTextElement: function() {
188 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
193 setCurrentElement: function(element, params) {
194 if(!(element instanceof documentElement.DocumentElement)) {
195 element = utils.findCanvasElement(element);
198 params = _.extend({caretTo: 'end'}, params);
199 var findFirstDirectTextChild = function(e, nodeToLand) {
200 var byBrowser = this.getCursor().getPosition().element;
201 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
203 var children = e.children();
204 for(var i = 0; i < children.length; i++) {
205 if(children[i] instanceof documentElement.DocumentTextElement)
210 var _markAsCurrent = function(element) {
211 if(element instanceof documentElement.DocumentTextElement) {
212 this.wrapper.find('.current-text-element').removeClass('current-text-element');
213 element.dom().addClass('current-text-element');
215 this.wrapper.find('.current-node-element').removeClass('current-node-element')
216 element._container().addClass('current-node-element');
217 this.publisher('currentElementChanged', element);
222 var isTextElement = element instanceof documentElement.DocumentTextElement,
223 nodeElementToLand = isTextElement ? element.parent() : element,
224 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
225 currentTextElement = this.getCurrentTextElement(),
226 currentNodeElement = this.getCurrentNodeElement();
228 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
229 this.wrapper.find('.current-text-element').removeClass('current-text-element');
231 if(textElementToLand) {
232 _markAsCurrent(textElementToLand);
233 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
234 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
235 if(!(textElementToLand.sameNode(currentTextElement)))
236 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
238 document.getSelection().removeAllRanges();
241 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
242 _markAsCurrent(nodeElementToLand);
244 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
248 _moveCaretToTextElement: function(element, where) {
249 var range = document.createRange(),
250 node = element.dom().contents()[0];
252 if(typeof where !== 'number') {
253 range.selectNodeContents(node);
255 range.setStart(node, where);
258 var collapseArg = true;
261 range.collapse(collapseArg);
263 var selection = document.getSelection();
265 selection.removeAllRanges();
266 selection.addRange(range);
267 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
270 setCursorPosition: function(position) {
272 this._moveCaretToTextElement(position.element, position.offset);
276 $.extend(Canvas.prototype.list, {
277 create: function(params) {
278 if(!(params.element1.parent().sameNode(params.element2.parent())))
281 var parent = params.element1.parent(),
282 canvas = params.element1.canvas;
284 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
285 var tmp = params.element1;
286 params.element1 = params.element2;
287 params.element2 = tmp;
290 var elementsToWrap = [];
292 var place = 'before';
293 parent.children().some(function(element) {
295 if(element.sameNode(params.element1))
297 if(place === 'inside') {
298 if(element instanceof documentElement.DocumentTextElement) {
299 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
300 if(element.children()[0].sameNode(params.element1))
301 params.element1 = element;
303 element.setWlxmlClass('item');
304 elementsToWrap.push(element);
306 if(_e.sameNode(params.element2))
310 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
312 if(parent.is('list')) {
313 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
314 item.exec('toggleBullet', false);
315 toret = listElement.parent();
320 params.element1.before(toret);
322 elementsToWrap.forEach(function(element) {
324 listElement.append(element);
327 extractItems: function(params) {
328 params = _.extend({merge: true}, params);
329 var list = params.element1.parent();
330 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
333 var idx1 = list.childIndex(params.element1),
334 idx2 = list.childIndex(params.element2),
337 succeedingItems = [],
338 items = list.children(),
339 listIsNested = list.parent().getWlxmlClass() === 'item',
340 canvas = params.element1.canvas,
344 var tmp = idx1; idx1 = idx2; idx2 = tmp;
347 items.forEach(function(item, idx) {
349 precedingItems.push(item);
350 else if(idx >= idx1 && idx <= idx2) {
351 extractedItems.push(item);
354 succeedingItems.push(item);
358 var reference = listIsNested ? list.parent() : list;
359 if(succeedingItems.length === 0) {
360 var reference_orig = reference;
361 extractedItems.forEach(function(item) {
362 reference.after(item);
365 item.setWlxmlClass(null);
367 if(precedingItems.length === 0)
368 reference_orig.detach();
369 } else if(precedingItems.length === 0) {
370 extractedItems.forEach(function(item) {
371 reference.before(item);
373 item.setWlxmlClass(null);
376 extractedItems.forEach(function(item) {
377 reference.after(item);
379 item.setWlxmlClass(null);
382 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
386 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
388 succeedingItems.forEach(function(item) {
389 secondList.append(item);
392 reference.after(toAdd);
394 if(!params.merge && listIsNested) {
395 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
399 areItemsOfTheSameList: function(params) {
400 var e1 = params.element1,
401 e2 = params.element2;
402 return e1.parent().sameNode(e2.parent())
403 && e1.parent().is('list');
408 var Cursor = function(canvas) {
409 this.canvas = canvas;
412 $.extend(Cursor.prototype, {
413 isSelecting: function() {
414 var selection = window.getSelection();
415 return !selection.isCollapsed;
417 isSelectingWithinElement: function() {
418 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
420 isSelectingSiblings: function() {
421 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
423 getPosition: function() {
424 return this.getSelectionAnchor();
426 getSelectionStart: function() {
427 return this.getSelectionBoundry('start');
429 getSelectionEnd: function() {
430 return this.getSelectionBoundry('end');
432 getSelectionAnchor: function() {
433 return this.getSelectionBoundry('anchor');
435 getSelectionFocus: function() {
436 return this.getSelectionBoundry('focus');
438 getSelectionBoundry: function(which) {
439 var selection = window.getSelection(),
440 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
441 focusElement = this.canvas.getDocumentElement(selection.focusNode);
443 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
446 if(which === 'anchor') {
448 element: anchorElement,
449 offset: selection.anchorOffset,
450 offsetAtBeginning: selection.anchorOffset === 0,
451 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
454 if(which === 'focus') {
456 element: focusElement,
457 offset: selection.focusOffset,
458 offsetAtBeginning: selection.focusOffset === 0,
459 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
466 if(anchorElement.parent().sameNode(focusElement.parent())) {
467 var parent = anchorElement.parent(),
468 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
470 if(which === 'start') {
471 element = anchorElement;
472 offset = selection.anchorOffset
474 else if(which === 'end') {
475 element = focusElement,
476 offset = selection.focusOffset
479 if(which === 'start') {
480 element = focusElement,
481 offset = selection.focusOffset
483 else if(which === 'end') {
484 element = anchorElement;
485 offset = selection.anchorOffset
489 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
490 if(which === 'start') {
491 element = anchorElement;
492 offset = selection.anchorOffset
494 element = focusElement;
495 offset = selection.focusOffset
499 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
503 offsetAtBeginning: offset === 0,
504 offsetAtEnd: nodeLen === offset
510 fromXMLDocument: function(wlxmlDocument, publisher) {
511 return new Canvas(wlxmlDocument, publisher);