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 this.wlxmlListener.listenTo(wlxmlDocument);
29 this.wlxmlDocument = wlxmlDocument;
31 this.setupEventHandling();
34 reloadRoot: function() {
35 var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
36 //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
39 this.wrapper.append(canvasDOM);
40 this.d = this.wrapper.children(0);
43 generateCanvasDOM: function(wlxmlNode) {
44 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
48 setupEventHandling: function() {
50 this.wrapper.on('keyup keydown keypress', function(e) {
51 keyboard.handleKey(e, this);
54 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
56 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
59 var observer = new MutationObserver(function(mutations) {
60 mutations.forEach(function(mutation) {
61 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
62 observer.disconnect();
63 if(mutation.target.data === '')
64 mutation.target.data = utils.unicode.ZWS;
65 else if(mutation.oldValue === utils.unicode.ZWS) {
66 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
67 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
69 observer.observe(canvas.d[0], config);
70 canvas.publisher('contentChanged');
72 var textElement = canvas.getDocumentElement(mutation.target),
73 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
75 textElement.data('wlxmlNode').setText(toSet);
79 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
80 observer.observe(this.d[0], config);
83 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
84 var el = canvas.getDocumentElement(e.currentTarget);
88 if(el instanceof documentElement.DocumentTextElement)
92 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
93 var el = canvas.getDocumentElement(e.currentTarget);
97 if(el instanceof documentElement.DocumentTextElement)
99 el.toggleLabel(false);
102 this.eventBus.on('elementToggled', function(toggle, element) {
104 canvas.setCurrentElement(element.getPreviousTextElement());
116 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
119 toggleElementHighlight: function(node, toggle) {
120 var element = utils.findCanvasElement(node);
121 element.toggleHighlight(toggle);
124 createNodeElement: function(params) {
125 return documentElement.DocumentNodeElement.create(params, this);
128 getDocumentElement: function(from) {
129 if(from instanceof HTMLElement || from instanceof Text) {
130 return documentElement.DocumentElement.fromHTMLElement(from, this);
133 getCursor: function() {
134 return new Cursor(this);
140 getCurrentNodeElement: function() {
141 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
144 getCurrentTextElement: function() {
145 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
150 setCurrentElement: function(element, params) {
151 if(!(element instanceof documentElement.DocumentElement)) {
152 element = utils.findCanvasElement(element);
155 params = _.extend({caretTo: 'end'}, params);
156 var findFirstDirectTextChild = function(e, nodeToLand) {
157 var byBrowser = this.getCursor().getPosition().element;
158 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
160 var children = e.children();
161 for(var i = 0; i < children.length; i++) {
162 if(children[i] instanceof documentElement.DocumentTextElement)
167 var _markAsCurrent = function(element) {
168 if(element instanceof documentElement.DocumentTextElement) {
169 this.wrapper.find('.current-text-element').removeClass('current-text-element');
170 element.dom().addClass('current-text-element');
172 this.wrapper.find('.current-node-element').removeClass('current-node-element')
173 element._container().addClass('current-node-element');
174 this.publisher('currentElementChanged', element);
179 var isTextElement = element instanceof documentElement.DocumentTextElement,
180 nodeElementToLand = isTextElement ? element.parent() : element,
181 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
182 currentTextElement = this.getCurrentTextElement(),
183 currentNodeElement = this.getCurrentNodeElement();
185 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
186 this.wrapper.find('.current-text-element').removeClass('current-text-element');
188 if(textElementToLand) {
189 _markAsCurrent(textElementToLand);
190 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
191 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
192 if(!(textElementToLand.sameNode(currentTextElement)))
193 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
195 document.getSelection().removeAllRanges();
198 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
199 _markAsCurrent(nodeElementToLand);
201 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
205 _moveCaretToTextElement: function(element, where) {
206 var range = document.createRange(),
207 node = element.dom().contents()[0];
209 if(typeof where !== 'number') {
210 range.selectNodeContents(node);
212 range.setStart(node, where);
215 var collapseArg = true;
218 range.collapse(collapseArg);
220 var selection = document.getSelection();
222 selection.removeAllRanges();
223 selection.addRange(range);
224 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
227 setCursorPosition: function(position) {
229 this._moveCaretToTextElement(position.element, position.offset);
233 $.extend(Canvas.prototype.list, {
234 create: function(params) {
235 if(!(params.element1.parent().sameNode(params.element2.parent())))
238 var parent = params.element1.parent(),
239 canvas = params.element1.canvas;
241 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
242 var tmp = params.element1;
243 params.element1 = params.element2;
244 params.element2 = tmp;
247 var elementsToWrap = [];
249 var place = 'before';
250 parent.children().some(function(element) {
252 if(element.sameNode(params.element1))
254 if(place === 'inside') {
255 if(element instanceof documentElement.DocumentTextElement) {
256 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
257 if(element.children()[0].sameNode(params.element1))
258 params.element1 = element;
260 element.setWlxmlClass('item');
261 elementsToWrap.push(element);
263 if(_e.sameNode(params.element2))
267 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
269 if(parent.is('list')) {
270 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
271 item.exec('toggleBullet', false);
272 toret = listElement.parent();
277 params.element1.before(toret);
279 elementsToWrap.forEach(function(element) {
281 listElement.append(element);
284 extractItems: function(params) {
285 params = _.extend({merge: true}, params);
286 var list = params.element1.parent();
287 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
290 var idx1 = list.childIndex(params.element1),
291 idx2 = list.childIndex(params.element2),
294 succeedingItems = [],
295 items = list.children(),
296 listIsNested = list.parent().getWlxmlClass() === 'item',
297 canvas = params.element1.canvas,
301 var tmp = idx1; idx1 = idx2; idx2 = tmp;
304 items.forEach(function(item, idx) {
306 precedingItems.push(item);
307 else if(idx >= idx1 && idx <= idx2) {
308 extractedItems.push(item);
311 succeedingItems.push(item);
315 var reference = listIsNested ? list.parent() : list;
316 if(succeedingItems.length === 0) {
317 var reference_orig = reference;
318 extractedItems.forEach(function(item) {
319 reference.after(item);
322 item.setWlxmlClass(null);
324 if(precedingItems.length === 0)
325 reference_orig.detach();
326 } else if(precedingItems.length === 0) {
327 extractedItems.forEach(function(item) {
328 reference.before(item);
330 item.setWlxmlClass(null);
333 extractedItems.forEach(function(item) {
334 reference.after(item);
336 item.setWlxmlClass(null);
339 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
343 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
345 succeedingItems.forEach(function(item) {
346 secondList.append(item);
349 reference.after(toAdd);
351 if(!params.merge && listIsNested) {
352 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
356 areItemsOfTheSameList: function(params) {
357 var e1 = params.element1,
358 e2 = params.element2;
359 return e1.parent().sameNode(e2.parent())
360 && e1.parent().is('list');
365 var Cursor = function(canvas) {
366 this.canvas = canvas;
369 $.extend(Cursor.prototype, {
370 isSelecting: function() {
371 var selection = window.getSelection();
372 return !selection.isCollapsed;
374 isSelectingWithinElement: function() {
375 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
377 isSelectingSiblings: function() {
378 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
380 getPosition: function() {
381 return this.getSelectionAnchor();
383 getSelectionStart: function() {
384 return this.getSelectionBoundry('start');
386 getSelectionEnd: function() {
387 return this.getSelectionBoundry('end');
389 getSelectionAnchor: function() {
390 return this.getSelectionBoundry('anchor');
392 getSelectionFocus: function() {
393 return this.getSelectionBoundry('focus');
395 getSelectionBoundry: function(which) {
396 var selection = window.getSelection(),
397 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
398 focusElement = this.canvas.getDocumentElement(selection.focusNode);
400 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
403 if(which === 'anchor') {
405 element: anchorElement,
406 offset: selection.anchorOffset,
407 offsetAtBeginning: selection.anchorOffset === 0,
408 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
411 if(which === 'focus') {
413 element: focusElement,
414 offset: selection.focusOffset,
415 offsetAtBeginning: selection.focusOffset === 0,
416 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
423 if(anchorElement.parent().sameNode(focusElement.parent())) {
424 var parent = anchorElement.parent(),
425 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
427 if(which === 'start') {
428 element = anchorElement;
429 offset = selection.anchorOffset
431 else if(which === 'end') {
432 element = focusElement,
433 offset = selection.focusOffset
436 if(which === 'start') {
437 element = focusElement,
438 offset = selection.focusOffset
440 else if(which === 'end') {
441 element = anchorElement;
442 offset = selection.anchorOffset
446 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
447 if(which === 'start') {
448 element = anchorElement;
449 offset = selection.anchorOffset
451 element = focusElement;
452 offset = selection.focusOffset
456 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
460 offsetAtBeginning: offset === 0,
461 offsetAtEnd: nodeLen === offset
467 fromXMLDocument: function(wlxmlDocument, publisher) {
468 return new Canvas(wlxmlDocument, publisher);