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);
37 this.wrapper.append(canvasDOM);
38 this.d = this.wrapper.children(0);
41 generateCanvasDOM: function(wlxmlNode) {
42 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
46 setupEventHandling: function() {
48 this.wrapper.on('keyup keydown keypress', function(e) {
49 keyboard.handleKey(e, this);
52 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
54 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
57 var observer = new MutationObserver(function(mutations) {
58 mutations.forEach(function(mutation) {
59 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
60 observer.disconnect();
61 if(mutation.target.data === '')
62 mutation.target.data = utils.unicode.ZWS;
63 else if(mutation.oldValue === utils.unicode.ZWS) {
64 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
65 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
67 observer.observe(canvas.d[0], config);
68 canvas.publisher('contentChanged');
70 var textElement = canvas.getDocumentElement(mutation.target),
71 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
73 textElement.data('wlxmlNode').setText(toSet);
77 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
78 observer.observe(this.d[0], config);
81 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
82 var el = canvas.getDocumentElement(e.currentTarget);
86 if(el instanceof documentElement.DocumentTextElement)
90 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
91 var el = canvas.getDocumentElement(e.currentTarget);
95 if(el instanceof documentElement.DocumentTextElement)
97 el.toggleLabel(false);
100 this.eventBus.on('elementToggled', function(toggle, element) {
102 canvas.setCurrentElement(element.getPreviousTextElement());
114 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
117 toggleElementHighlight: function(node, toggle) {
118 var element = utils.findCanvasElement(node);
119 element.toggleHighlight(toggle);
122 createNodeElement: function(params) {
123 return documentElement.DocumentNodeElement.create(params, this);
126 getDocumentElement: function(from) {
127 if(from instanceof HTMLElement || from instanceof Text) {
128 return documentElement.DocumentElement.fromHTMLElement(from, this);
131 getCursor: function() {
132 return new Cursor(this);
138 getCurrentNodeElement: function() {
139 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
142 getCurrentTextElement: function() {
143 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
148 setCurrentElement: function(element, params) {
149 if(!(element instanceof documentElement.DocumentElement)) {
150 element = utils.findCanvasElement(element);
153 params = _.extend({caretTo: 'end'}, params);
154 var findFirstDirectTextChild = function(e, nodeToLand) {
155 var byBrowser = this.getCursor().getPosition().element;
156 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
158 var children = e.children();
159 for(var i = 0; i < children.length; i++) {
160 if(children[i] instanceof documentElement.DocumentTextElement)
165 var _markAsCurrent = function(element) {
166 if(element instanceof documentElement.DocumentTextElement) {
167 this.wrapper.find('.current-text-element').removeClass('current-text-element');
168 element.dom().addClass('current-text-element');
170 this.wrapper.find('.current-node-element').removeClass('current-node-element')
171 element._container().addClass('current-node-element');
172 this.publisher('currentElementChanged', element);
177 var isTextElement = element instanceof documentElement.DocumentTextElement,
178 nodeElementToLand = isTextElement ? element.parent() : element,
179 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
180 currentTextElement = this.getCurrentTextElement(),
181 currentNodeElement = this.getCurrentNodeElement();
183 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
184 this.wrapper.find('.current-text-element').removeClass('current-text-element');
186 if(textElementToLand) {
187 _markAsCurrent(textElementToLand);
188 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
189 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
190 if(!(textElementToLand.sameNode(currentTextElement)))
191 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
193 document.getSelection().removeAllRanges();
196 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
197 _markAsCurrent(nodeElementToLand);
199 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
203 _moveCaretToTextElement: function(element, where) {
204 var range = document.createRange(),
205 node = element.dom().contents()[0];
207 if(typeof where !== 'number') {
208 range.selectNodeContents(node);
210 range.setStart(node, where);
213 var collapseArg = true;
216 range.collapse(collapseArg);
218 var selection = document.getSelection();
220 selection.removeAllRanges();
221 selection.addRange(range);
222 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
225 setCursorPosition: function(position) {
227 this._moveCaretToTextElement(position.element, position.offset);
231 $.extend(Canvas.prototype.list, {
232 create: function(params) {
233 if(!(params.element1.parent().sameNode(params.element2.parent())))
236 var parent = params.element1.parent(),
237 canvas = params.element1.canvas;
239 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
240 var tmp = params.element1;
241 params.element1 = params.element2;
242 params.element2 = tmp;
245 var elementsToWrap = [];
247 var place = 'before';
248 parent.children().some(function(element) {
250 if(element.sameNode(params.element1))
252 if(place === 'inside') {
253 if(element instanceof documentElement.DocumentTextElement) {
254 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
255 if(element.children()[0].sameNode(params.element1))
256 params.element1 = element;
258 element.setWlxmlClass('item');
259 elementsToWrap.push(element);
261 if(_e.sameNode(params.element2))
265 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
267 if(parent.is('list')) {
268 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
269 item.exec('toggleBullet', false);
270 toret = listElement.parent();
275 params.element1.before(toret);
277 elementsToWrap.forEach(function(element) {
279 listElement.append(element);
282 extractItems: function(params) {
283 params = _.extend({merge: true}, params);
284 var list = params.element1.parent();
285 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
288 var idx1 = list.childIndex(params.element1),
289 idx2 = list.childIndex(params.element2),
292 succeedingItems = [],
293 items = list.children(),
294 listIsNested = list.parent().getWlxmlClass() === 'item',
295 canvas = params.element1.canvas,
299 var tmp = idx1; idx1 = idx2; idx2 = tmp;
302 items.forEach(function(item, idx) {
304 precedingItems.push(item);
305 else if(idx >= idx1 && idx <= idx2) {
306 extractedItems.push(item);
309 succeedingItems.push(item);
313 var reference = listIsNested ? list.parent() : list;
314 if(succeedingItems.length === 0) {
315 var reference_orig = reference;
316 extractedItems.forEach(function(item) {
317 reference.after(item);
320 item.setWlxmlClass(null);
322 if(precedingItems.length === 0)
323 reference_orig.detach();
324 } else if(precedingItems.length === 0) {
325 extractedItems.forEach(function(item) {
326 reference.before(item);
328 item.setWlxmlClass(null);
331 extractedItems.forEach(function(item) {
332 reference.after(item);
334 item.setWlxmlClass(null);
337 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
341 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
343 succeedingItems.forEach(function(item) {
344 secondList.append(item);
347 reference.after(toAdd);
349 if(!params.merge && listIsNested) {
350 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
354 areItemsOfTheSameList: function(params) {
355 var e1 = params.element1,
356 e2 = params.element2;
357 return e1.parent().sameNode(e2.parent())
358 && e1.parent().is('list');
363 var Cursor = function(canvas) {
364 this.canvas = canvas;
367 $.extend(Cursor.prototype, {
368 isSelecting: function() {
369 var selection = window.getSelection();
370 return !selection.isCollapsed;
372 isSelectingWithinElement: function() {
373 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
375 isSelectingSiblings: function() {
376 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
378 getPosition: function() {
379 return this.getSelectionAnchor();
381 getSelectionStart: function() {
382 return this.getSelectionBoundry('start');
384 getSelectionEnd: function() {
385 return this.getSelectionBoundry('end');
387 getSelectionAnchor: function() {
388 return this.getSelectionBoundry('anchor');
390 getSelectionFocus: function() {
391 return this.getSelectionBoundry('focus');
393 getSelectionBoundry: function(which) {
394 var selection = window.getSelection(),
395 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
396 focusElement = this.canvas.getDocumentElement(selection.focusNode);
398 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
401 if(which === 'anchor') {
403 element: anchorElement,
404 offset: selection.anchorOffset,
405 offsetAtBeginning: selection.anchorOffset === 0,
406 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
409 if(which === 'focus') {
411 element: focusElement,
412 offset: selection.focusOffset,
413 offsetAtBeginning: selection.focusOffset === 0,
414 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
421 if(anchorElement.parent().sameNode(focusElement.parent())) {
422 var parent = anchorElement.parent(),
423 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
425 if(which === 'start') {
426 element = anchorElement;
427 offset = selection.anchorOffset
429 else if(which === 'end') {
430 element = focusElement,
431 offset = selection.focusOffset
434 if(which === 'start') {
435 element = focusElement,
436 offset = selection.focusOffset
438 else if(which === 'end') {
439 element = anchorElement;
440 offset = selection.anchorOffset
444 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
445 if(which === 'start') {
446 element = anchorElement;
447 offset = selection.anchorOffset
449 element = focusElement;
450 offset = selection.focusOffset
454 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
458 offsetAtBeginning: offset === 0,
459 offsetAtEnd: nodeLen === offset
465 fromXMLDocument: function(wlxmlDocument, publisher) {
466 return new Canvas(wlxmlDocument, publisher);