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.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', element);
222 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
223 _markAsCurrent(nodeElementToLand);
224 if(!textElementToLand)
225 document.getSelection().removeAllRanges();
226 this.publisher('currentNodeElementSet', nodeElementToLand);
230 _moveCaretToTextElement: function(element, where) {
231 var range = document.createRange(),
232 node = element.dom().contents()[0];
234 if(typeof where !== 'number') {
235 range.selectNodeContents(node);
237 range.setStart(node, where);
240 var collapseArg = true;
243 range.collapse(collapseArg);
245 var selection = document.getSelection();
247 selection.removeAllRanges();
248 selection.addRange(range);
249 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
252 setCursorPosition: function(position) {
254 this._moveCaretToTextElement(position.element, position.offset);
258 $.extend(Canvas.prototype.list, {
259 create: function(params) {
260 if(!(params.element1.parent().sameNode(params.element2.parent())))
263 var parent = params.element1.parent();
265 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
266 var tmp = params.element1;
267 params.element1 = params.element2;
268 params.element2 = tmp;
271 var elementsToWrap = [];
273 var place = 'before';
275 parent.children().some(function(element) {
277 if(element.sameNode(params.element1))
279 if(place === 'inside') {
280 if(element instanceof documentElement.DocumentTextElement) {
281 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
282 if(element.children()[0].sameNode(params.element1))
283 params.element1 = element;
285 element.setWlxmlClass('item');
286 elementsToWrap.push(element);
288 if(_e.sameNode(params.element2))
292 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
295 if(parent.is('list')) {
296 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
297 toret = listElement.parent();
302 params.element1.before(toret);
304 elementsToWrap.forEach(function(element) {
306 listElement.append(element);
309 extractItems: function(params) {
310 params = _.extend({merge: true}, params);
311 var list = params.element1.parent();
312 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
315 var idx1 = list.childIndex(params.element1),
316 idx2 = list.childIndex(params.element2),
319 succeedingItems = [],
320 items = list.children(),
321 listIsNested = list.parent().getWlxmlClass() === 'item',
325 var tmp = idx1; idx1 = idx2; idx2 = tmp;
328 items.forEach(function(item, idx) {
330 precedingItems.push(item);
331 else if(idx >= idx1 && idx <= idx2) {
332 extractedItems.push(item);
335 succeedingItems.push(item);
339 var reference = listIsNested ? list.parent() : list;
340 if(succeedingItems.length === 0) {
341 var reference_orig = reference;
342 extractedItems.forEach(function(item) {
343 reference.after(item);
346 item.setWlxmlClass(null);
348 if(precedingItems.length === 0)
349 reference_orig.detach();
350 } else if(precedingItems.length === 0) {
351 extractedItems.forEach(function(item) {
352 reference.before(item);
354 item.setWlxmlClass(null);
357 extractedItems.forEach(function(item) {
358 reference.after(item);
360 item.setWlxmlClass(null);
363 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
367 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
369 succeedingItems.forEach(function(item) {
370 secondList.append(item);
373 reference.after(toAdd);
375 if(!params.merge && listIsNested) {
376 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
380 areItemsOfTheSameList: function(params) {
381 var e1 = params.element1,
382 e2 = params.element2;
383 return e1.parent().sameNode(e2.parent())
384 && e1.parent().is('list');
389 var Cursor = function(canvas) {
390 this.canvas = canvas;
393 $.extend(Cursor.prototype, {
394 isSelecting: function() {
395 var selection = window.getSelection();
396 return !selection.isCollapsed;
398 isSelectingWithinElement: function() {
399 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
401 isSelectingSiblings: function() {
402 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
404 getPosition: function() {
405 return this.getSelectionAnchor();
407 getSelectionStart: function() {
408 return this.getSelectionBoundry('start');
410 getSelectionEnd: function() {
411 return this.getSelectionBoundry('end');
413 getSelectionAnchor: function() {
414 return this.getSelectionBoundry('anchor');
416 getSelectionBoundry: function(which) {
417 var selection = window.getSelection(),
418 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
419 focusElement = this.canvas.getDocumentElement(selection.focusNode);
421 if(which === 'anchor') {
423 element: anchorElement,
424 offset: selection.anchorOffset
431 if(anchorElement.parent().sameNode(focusElement.parent())) {
432 var parent = anchorElement.parent(),
433 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
435 if(which === 'start') {
436 element = anchorElement;
437 offset = selection.anchorOffset;
439 else if(which === 'end') {
440 element = focusElement,
441 offset = selection.focusOffset;
444 if(which === 'start') {
445 element = focusElement,
446 offset = selection.focusOffset
448 else if(which === 'end') {
449 element = anchorElement;
450 offset = selection.anchorOffset;
454 // TODO: Handle order
455 if(which === 'start') {
456 element = anchorElement;
457 offset = selection.anchorOffset
459 element = focusElement;
460 offset = selection.focusOffset
472 fromXML: function(xml, publisher) {
473 return new Canvas(xml, publisher);