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 elements = position.element.split({offset: position.offset}),
82 if(position.offsetAtBeginning)
83 newEmpty = elements.first;
84 else if(position.offsetAtEnd)
85 newEmpty = elements.second;
87 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
88 canvas.setCurrentElement(goto);
94 this.wrapper.on('keyup', function(e) {
95 if(e.which >= 37 && e.which <= 40)
96 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
99 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
101 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
116 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
119 wrapText: function(params) {
120 params = _.extend({textNodeIdx: 0}, params);
121 if(typeof params.textNodeIdx === 'number')
122 params.textNodeIdx = [params.textNodeIdx];
124 var childrenInside = params.inside.children(),
125 idx1 = Math.min.apply(Math, params.textNodeIdx),
126 idx2 = Math.max.apply(Math, params.textNodeIdx),
127 textNode1 = childrenInside[idx1],
128 textNode2 = childrenInside[idx2],
129 sameNode = textNode1.sameNode(textNode2),
130 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
131 prefixInside = textNode1.getText().substr(params.offsetStart),
132 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
133 suffixOutside = textNode2.getText().substr(params.offsetEnd)
136 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
137 textNode1.after(wrapperElement);
140 if(prefixOutside.length > 0)
141 wrapperElement.before({text:prefixOutside});
143 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
144 wrapperElement.append({text: core});
147 if(prefixInside.length > 0)
148 wrapperElement.append({text: prefixInside});
149 for(var i = idx1 + 1; i < idx2; i++) {
150 wrapperElement.append(childrenInside[i]);
152 if(suffixInside.length > 0)
153 wrapperElement.append({text: suffixInside});
155 if(suffixOutside.length > 0)
156 wrapperElement.after({text: suffixOutside});
157 return wrapperElement;
159 getDocumentElement: function(from) {
160 if(from instanceof HTMLElement || from instanceof Text) {
161 return documentElement.DocumentElement.fromHTMLElement(from, this);
164 getCursor: function() {
165 return new Cursor(this);
172 highlightElement: function(element) {
173 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
174 element.dom().addClass('highlighted-element');
177 dimElement: function(element) {
178 element.dom().removeClass('highlighted-element');
181 getCurrentNodeElement: function() {
182 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
185 getCurrentTextElement: function() {
186 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
191 setCurrentElement: function(element, params) {
192 params = _.extend({caretTo: 'end'}, params);
193 var findFirstDirectTextChild = function(e, nodeToLand) {
194 var byBrowser = this.getCursor().getPosition().element;
195 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
197 var children = e.children();
198 for(var i = 0; i < children.length; i++) {
199 if(children[i] instanceof documentElement.DocumentTextElement)
204 var _markAsCurrent = function(element) {
205 if(element instanceof documentElement.DocumentTextElement) {
206 this.wrapper.find('.current-text-element').removeClass('current-text-element');
207 element.dom().addClass('current-text-element');
209 this.wrapper.find('.current-node-element').removeClass('current-node-element')
210 element.dom().addClass('current-node-element');
211 this.publisher('currentElementChanged', element);
216 var isTextElement = element instanceof documentElement.DocumentTextElement,
217 nodeElementToLand = isTextElement ? element.parent() : element,
218 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
219 currentTextElement = this.getCurrentTextElement(),
220 currentNodeElement = this.getCurrentNodeElement();
222 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
223 this.wrapper.find('.current-text-element').removeClass('current-text-element');
225 if(textElementToLand) {
226 _markAsCurrent(textElementToLand);
227 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
228 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
229 if(!(textElementToLand.sameNode(currentTextElement)))
230 this.publisher('currentTextElementSet', textElementToLand);
232 document.getSelection().removeAllRanges();
235 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
236 _markAsCurrent(nodeElementToLand);
238 this.publisher('currentNodeElementSet', nodeElementToLand);
242 _moveCaretToTextElement: function(element, where) {
243 var range = document.createRange(),
244 node = element.dom().contents()[0];
246 if(typeof where !== 'number') {
247 range.selectNodeContents(node);
249 range.setStart(node, where);
252 var collapseArg = true;
255 range.collapse(collapseArg);
257 var selection = document.getSelection();
259 selection.removeAllRanges();
260 selection.addRange(range);
261 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
264 setCursorPosition: function(position) {
266 this._moveCaretToTextElement(position.element, position.offset);
270 $.extend(Canvas.prototype.list, {
271 create: function(params) {
272 if(!(params.element1.parent().sameNode(params.element2.parent())))
275 var parent = params.element1.parent();
277 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
278 var tmp = params.element1;
279 params.element1 = params.element2;
280 params.element2 = tmp;
283 var elementsToWrap = [];
285 var place = 'before';
287 parent.children().some(function(element) {
289 if(element.sameNode(params.element1))
291 if(place === 'inside') {
292 if(element instanceof documentElement.DocumentTextElement) {
293 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
294 if(element.children()[0].sameNode(params.element1))
295 params.element1 = element;
297 element.setWlxmlClass('item');
298 elementsToWrap.push(element);
300 if(_e.sameNode(params.element2))
304 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
307 if(parent.is('list')) {
308 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
309 toret = listElement.parent();
314 params.element1.before(toret);
316 elementsToWrap.forEach(function(element) {
318 listElement.append(element);
321 extractItems: function(params) {
322 params = _.extend({merge: true}, params);
323 var list = params.element1.parent();
324 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
327 var idx1 = list.childIndex(params.element1),
328 idx2 = list.childIndex(params.element2),
331 succeedingItems = [],
332 items = list.children(),
333 listIsNested = list.parent().getWlxmlClass() === 'item',
337 var tmp = idx1; idx1 = idx2; idx2 = tmp;
340 items.forEach(function(item, idx) {
342 precedingItems.push(item);
343 else if(idx >= idx1 && idx <= idx2) {
344 extractedItems.push(item);
347 succeedingItems.push(item);
351 var reference = listIsNested ? list.parent() : list;
352 if(succeedingItems.length === 0) {
353 var reference_orig = reference;
354 extractedItems.forEach(function(item) {
355 reference.after(item);
358 item.setWlxmlClass(null);
360 if(precedingItems.length === 0)
361 reference_orig.detach();
362 } else if(precedingItems.length === 0) {
363 extractedItems.forEach(function(item) {
364 reference.before(item);
366 item.setWlxmlClass(null);
369 extractedItems.forEach(function(item) {
370 reference.after(item);
372 item.setWlxmlClass(null);
375 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
379 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
381 succeedingItems.forEach(function(item) {
382 secondList.append(item);
385 reference.after(toAdd);
387 if(!params.merge && listIsNested) {
388 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
392 areItemsOfTheSameList: function(params) {
393 var e1 = params.element1,
394 e2 = params.element2;
395 return e1.parent().sameNode(e2.parent())
396 && e1.parent().is('list');
401 var Cursor = function(canvas) {
402 this.canvas = canvas;
405 $.extend(Cursor.prototype, {
406 isSelecting: function() {
407 var selection = window.getSelection();
408 return !selection.isCollapsed;
410 isSelectingWithinElement: function() {
411 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
413 isSelectingSiblings: function() {
414 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
416 getPosition: function() {
417 return this.getSelectionAnchor();
419 getSelectionStart: function() {
420 return this.getSelectionBoundry('start');
422 getSelectionEnd: function() {
423 return this.getSelectionBoundry('end');
425 getSelectionAnchor: function() {
426 return this.getSelectionBoundry('anchor');
428 getSelectionBoundry: function(which) {
429 var selection = window.getSelection(),
430 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
431 focusElement = this.canvas.getDocumentElement(selection.focusNode);
433 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
436 if(which === 'anchor') {
438 element: anchorElement,
439 offset: selection.anchorOffset,
440 offsetAtBeginning: selection.anchorOffset === 0,
441 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
448 if(anchorElement.parent().sameNode(focusElement.parent())) {
449 var parent = anchorElement.parent(),
450 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
452 if(which === 'start') {
453 element = anchorElement;
454 offset = selection.anchorOffset;
456 else if(which === 'end') {
457 element = focusElement,
458 offset = selection.focusOffset;
461 if(which === 'start') {
462 element = focusElement,
463 offset = selection.focusOffset
465 else if(which === 'end') {
466 element = anchorElement;
467 offset = selection.anchorOffset;
471 // TODO: Handle order
472 if(which === 'start') {
473 element = anchorElement;
474 offset = selection.anchorOffset
476 element = focusElement;
477 offset = selection.focusOffset
484 offsetAtBeginning: offset === 0,
485 offsetAtEnd: element.getText().length === offset
491 fromXML: function(xml, publisher) {
492 return new Canvas(xml, publisher);