2 'libs/jquery-1.9.1.min',
4 'modules/documentCanvas/canvas/documentElement'
5 ], function($, _, documentElement) {
9 var Canvas = function(wlxml, publisher) {
10 this.loadWlxml(wlxml);
11 this.publisher = publisher ? publisher : function() {};
14 $.extend(Canvas.prototype, {
16 loadWlxml: function(wlxml) {
17 var d = wlxml ? $($.trim(wlxml)) : null;
19 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
20 this.wrapper.append(d);
22 this.wrapper.find('*').replaceWith(function() {
23 var currentTag = $(this);
24 if(currentTag.attr('wlxml-tag'))
26 var element = documentElement.DocumentNodeElement.createDOM({
27 tag: currentTag.prop('tagName').toLowerCase(),
28 klass: currentTag.attr('class')
31 element.append(currentTag.contents());
35 this.wrapper.find(':not(iframe)').addBack().contents()
36 .filter(function() {return this.nodeType === Node.TEXT_NODE})
41 // TODO: use DocumentElement API
42 var spanParent = el.parent().attr('wlxml-tag') === 'span',
43 spanBefore = el.prev().length > 0 && $(el.prev()[0]).attr('wlxml-tag') === 'span',
44 spanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
46 if(spanParent || spanBefore || spanAfter) {
47 var startSpace = /\s/g.test(this.data.substr(0,1));
48 var endSpace = /\s/g.test(this.data.substr(-1)) && this.data.length > 1;
49 var trimmed = $.trim(this.data);
50 this.data = (startSpace && (spanParent || spanBefore) ? ' ' : '')
52 + (endSpace && (spanParent || spanAfter) ? ' ' : '');
55 var oldLength = this.data.length;
56 this.data = $.trim(this.data);
57 if(this.data.length === 0 && oldLength > 0 && el.parent().contents().length === 1)
59 if(this.data.length === 0) {
61 return true; // continue
65 var element = documentElement.DocumentTextElement.create({text: this.data});
66 $(this).replaceWith(element.dom());
69 this.d = this.wrapper.children(0);
72 this.wrapper.on('keydown', function(e) {
75 var cursor = canvas.getCursor();
76 if(!cursor.isSelecting()) {
77 var position = cursor.getPosition();
78 position.element.split({offset: position.offset});
83 this.wrapper.on('keyup', function(e) {
84 if(e.which >= 37 && e.which <= 40)
85 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
88 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
90 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
105 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
108 wrapText: function(params) {
109 params = _.extend({textNodeIdx: 0}, params);
110 if(typeof params.textNodeIdx === 'number')
111 params.textNodeIdx = [params.textNodeIdx];
113 var childrenInside = params.inside.children(),
114 idx1 = Math.min.apply(Math, params.textNodeIdx),
115 idx2 = Math.max.apply(Math, params.textNodeIdx),
116 textNode1 = childrenInside[idx1],
117 textNode2 = childrenInside[idx2],
118 sameNode = textNode1.sameNode(textNode2),
119 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
120 prefixInside = textNode1.getText().substr(params.offsetStart),
121 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
122 suffixOutside = textNode2.getText().substr(params.offsetEnd)
125 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
126 textNode1.after(wrapperElement);
129 if(prefixOutside.length > 0)
130 wrapperElement.before({text:prefixOutside});
132 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
133 wrapperElement.append({text: core});
136 if(prefixInside.length > 0)
137 wrapperElement.append({text: prefixInside});
138 for(var i = idx1 + 1; i < idx2; i++) {
139 wrapperElement.append(childrenInside[i]);
141 if(suffixInside.length > 0)
142 wrapperElement.append({text: suffixInside});
144 if(suffixOutside.length > 0)
145 wrapperElement.after({text: suffixOutside});
146 return wrapperElement;
148 getDocumentElement: function(from) {
149 if(from instanceof HTMLElement || from instanceof Text) {
150 return documentElement.DocumentElement.fromHTMLElement(from, this);
153 getCursor: function() {
154 return new Cursor(this);
161 highlightElement: function(element) {
162 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
163 element.dom().addClass('highlighted-element');
166 dimElement: function(element) {
167 element.dom().removeClass('highlighted-element');
170 getCurrentNodeElement: function() {
171 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
174 getCurrentTextElement: function() {
175 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
180 setCurrentElement: function(element, params) {
181 params = _.extend({caretTo: 'end'}, params);
182 var findFirstDirectTextChild = function(e, nodeToLand) {
183 var byBrowser = this.getCursor().getPosition().element;
184 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
186 var children = e.children();
187 for(var i = 0; i < children.length; i++) {
188 if(children[i] instanceof documentElement.DocumentTextElement)
193 var _markAsCurrent = function(element) {
194 if(element instanceof documentElement.DocumentTextElement) {
195 this.wrapper.find('.current-text-element').removeClass('current-text-element');
196 element.dom().addClass('current-text-element');
198 this.wrapper.find('.current-node-element').removeClass('current-node-element')
199 element.dom().addClass('current-node-element');
200 this.publisher('currentElementChanged', element);
205 var isTextElement = element instanceof documentElement.DocumentTextElement,
206 nodeElementToLand = isTextElement ? element.parent() : element,
207 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
208 currentTextElement = this.getCurrentTextElement(),
209 currentNodeElement = this.getCurrentNodeElement();
211 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
212 this.wrapper.find('.current-text-element').removeClass('current-text-element');
214 if(textElementToLand) {
215 _markAsCurrent(textElementToLand);
216 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
217 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
218 if(!(textElementToLand.sameNode(currentTextElement)))
219 this.publisher('currentTextElementSet', textElementToLand);
221 document.getSelection().removeAllRanges();
224 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
225 _markAsCurrent(nodeElementToLand);
227 this.publisher('currentNodeElementSet', nodeElementToLand);
231 _moveCaretToTextElement: function(element, where) {
232 var range = document.createRange(),
233 node = element.dom().contents()[0];
235 if(typeof where !== 'number') {
236 range.selectNodeContents(node);
238 range.setStart(node, where);
241 var collapseArg = true;
244 range.collapse(collapseArg);
246 var selection = document.getSelection();
248 selection.removeAllRanges();
249 selection.addRange(range);
250 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
253 setCursorPosition: function(position) {
255 this._moveCaretToTextElement(position.element, position.offset);
259 $.extend(Canvas.prototype.list, {
260 create: function(params) {
261 if(!(params.element1.parent().sameNode(params.element2.parent())))
264 var parent = params.element1.parent();
266 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
267 var tmp = params.element1;
268 params.element1 = params.element2;
269 params.element2 = tmp;
272 var elementsToWrap = [];
274 var place = 'before';
276 parent.children().some(function(element) {
278 if(element.sameNode(params.element1))
280 if(place === 'inside') {
281 if(element instanceof documentElement.DocumentTextElement) {
282 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
283 if(element.children()[0].sameNode(params.element1))
284 params.element1 = element;
286 element.setWlxmlClass('item');
287 elementsToWrap.push(element);
289 if(_e.sameNode(params.element2))
293 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
296 if(parent.is('list')) {
297 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
298 toret = listElement.parent();
303 params.element1.before(toret);
305 elementsToWrap.forEach(function(element) {
307 listElement.append(element);
310 extractItems: function(params) {
311 params = _.extend({merge: true}, params);
312 var list = params.element1.parent();
313 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
316 var idx1 = list.childIndex(params.element1),
317 idx2 = list.childIndex(params.element2),
320 succeedingItems = [],
321 items = list.children(),
322 listIsNested = list.parent().getWlxmlClass() === 'item',
326 var tmp = idx1; idx1 = idx2; idx2 = tmp;
329 items.forEach(function(item, idx) {
331 precedingItems.push(item);
332 else if(idx >= idx1 && idx <= idx2) {
333 extractedItems.push(item);
336 succeedingItems.push(item);
340 var reference = listIsNested ? list.parent() : list;
341 if(succeedingItems.length === 0) {
342 var reference_orig = reference;
343 extractedItems.forEach(function(item) {
344 reference.after(item);
347 item.setWlxmlClass(null);
349 if(precedingItems.length === 0)
350 reference_orig.detach();
351 } else if(precedingItems.length === 0) {
352 extractedItems.forEach(function(item) {
353 reference.before(item);
355 item.setWlxmlClass(null);
358 extractedItems.forEach(function(item) {
359 reference.after(item);
361 item.setWlxmlClass(null);
364 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
368 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
370 succeedingItems.forEach(function(item) {
371 secondList.append(item);
374 reference.after(toAdd);
376 if(!params.merge && listIsNested) {
377 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
381 areItemsOfTheSameList: function(params) {
382 var e1 = params.element1,
383 e2 = params.element2;
384 return e1.parent().sameNode(e2.parent())
385 && e1.parent().is('list');
390 var Cursor = function(canvas) {
391 this.canvas = canvas;
394 $.extend(Cursor.prototype, {
395 isSelecting: function() {
396 var selection = window.getSelection();
397 return !selection.isCollapsed;
399 isSelectingWithinElement: function() {
400 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
402 isSelectingSiblings: function() {
403 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
405 getPosition: function() {
406 return this.getSelectionAnchor();
408 getSelectionStart: function() {
409 return this.getSelectionBoundry('start');
411 getSelectionEnd: function() {
412 return this.getSelectionBoundry('end');
414 getSelectionAnchor: function() {
415 return this.getSelectionBoundry('anchor');
417 getSelectionBoundry: function(which) {
418 var selection = window.getSelection(),
419 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
420 focusElement = this.canvas.getDocumentElement(selection.focusNode);
422 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
425 if(which === 'anchor') {
427 element: anchorElement,
428 offset: selection.anchorOffset
435 if(anchorElement.parent().sameNode(focusElement.parent())) {
436 var parent = anchorElement.parent(),
437 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
439 if(which === 'start') {
440 element = anchorElement;
441 offset = selection.anchorOffset;
443 else if(which === 'end') {
444 element = focusElement,
445 offset = selection.focusOffset;
448 if(which === 'start') {
449 element = focusElement,
450 offset = selection.focusOffset
452 else if(which === 'end') {
453 element = anchorElement;
454 offset = selection.anchorOffset;
458 // TODO: Handle order
459 if(which === 'start') {
460 element = anchorElement;
461 offset = selection.anchorOffset
463 element = focusElement;
464 offset = selection.focusOffset
476 fromXML: function(xml, publisher) {
477 return new Canvas(xml, publisher);