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'))
28 for(var i = 0; i < this.attributes.length; i++) {
29 var attr = this.attributes[i];
30 if(attr.name.substr(0, 5) === 'meta-')
31 meta[attr.name.substr(5)] = attr.value;
34 var element = documentElement.DocumentNodeElement.createDOM({
35 tag: currentTag.prop('tagName').toLowerCase(),
36 klass: currentTag.attr('class'),
40 element.append(currentTag.contents());
44 this.wrapper.find(':not(iframe)').addBack().contents()
45 .filter(function() {return this.nodeType === Node.TEXT_NODE})
50 // TODO: use DocumentElement API
51 var spanParent = el.parent().attr('wlxml-tag') === 'span',
52 spanBefore = el.prev().length > 0 && $(el.prev()[0]).attr('wlxml-tag') === 'span',
53 spanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
55 if(spanParent || spanBefore || spanAfter) {
56 var startSpace = /\s/g.test(this.data.substr(0,1));
57 var endSpace = /\s/g.test(this.data.substr(-1)) && this.data.length > 1;
58 var trimmed = $.trim(this.data);
59 this.data = (startSpace && (spanParent || spanBefore) ? ' ' : '')
61 + (endSpace && (spanParent || spanAfter) ? ' ' : '');
64 var oldLength = this.data.length;
65 this.data = $.trim(this.data);
66 if(this.data.length === 0 && oldLength > 0 && el.parent().contents().length === 1)
68 if(this.data.length === 0) {
70 return true; // continue
74 var element = documentElement.DocumentTextElement.create({text: this.data});
75 $(this).replaceWith(element.dom());
78 this.d = this.wrapper.children(0);
81 this.wrapper.on('keydown', function(e) {
84 var cursor = canvas.getCursor();
85 if(!cursor.isSelecting()) {
86 var position = cursor.getPosition(),
87 elements = position.element.split({offset: position.offset}),
91 if(position.offsetAtBeginning)
92 newEmpty = elements.first;
93 else if(position.offsetAtEnd)
94 newEmpty = elements.second;
96 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
97 canvas.setCurrentElement(goto);
103 this.wrapper.on('keyup', function(e) {
104 if(e.which >= 37 && e.which <= 40)
105 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
108 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
110 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
125 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
128 wrapText: function(params) {
129 params = _.extend({textNodeIdx: 0}, params);
130 if(typeof params.textNodeIdx === 'number')
131 params.textNodeIdx = [params.textNodeIdx];
133 var childrenInside = params.inside.children(),
134 idx1 = Math.min.apply(Math, params.textNodeIdx),
135 idx2 = Math.max.apply(Math, params.textNodeIdx),
136 textNode1 = childrenInside[idx1],
137 textNode2 = childrenInside[idx2],
138 sameNode = textNode1.sameNode(textNode2),
139 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
140 prefixInside = textNode1.getText().substr(params.offsetStart),
141 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
142 suffixOutside = textNode2.getText().substr(params.offsetEnd)
145 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
146 textNode1.after(wrapperElement);
149 if(prefixOutside.length > 0)
150 wrapperElement.before({text:prefixOutside});
152 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
153 wrapperElement.append({text: core});
156 if(prefixInside.length > 0)
157 wrapperElement.append({text: prefixInside});
158 for(var i = idx1 + 1; i < idx2; i++) {
159 wrapperElement.append(childrenInside[i]);
161 if(suffixInside.length > 0)
162 wrapperElement.append({text: suffixInside});
164 if(suffixOutside.length > 0)
165 wrapperElement.after({text: suffixOutside});
166 return wrapperElement;
168 getDocumentElement: function(from) {
169 if(from instanceof HTMLElement || from instanceof Text) {
170 return documentElement.DocumentElement.fromHTMLElement(from, this);
173 getCursor: function() {
174 return new Cursor(this);
181 highlightElement: function(element) {
182 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
183 element.dom().addClass('highlighted-element');
186 dimElement: function(element) {
187 element.dom().removeClass('highlighted-element');
190 getCurrentNodeElement: function() {
191 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
194 getCurrentTextElement: function() {
195 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
200 setCurrentElement: function(element, params) {
201 params = _.extend({caretTo: 'end'}, params);
202 var findFirstDirectTextChild = function(e, nodeToLand) {
203 var byBrowser = this.getCursor().getPosition().element;
204 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
206 var children = e.children();
207 for(var i = 0; i < children.length; i++) {
208 if(children[i] instanceof documentElement.DocumentTextElement)
213 var _markAsCurrent = function(element) {
214 if(element instanceof documentElement.DocumentTextElement) {
215 this.wrapper.find('.current-text-element').removeClass('current-text-element');
216 element.dom().addClass('current-text-element');
218 this.wrapper.find('.current-node-element').removeClass('current-node-element')
219 element.dom().addClass('current-node-element');
220 this.publisher('currentElementChanged', element);
225 var isTextElement = element instanceof documentElement.DocumentTextElement,
226 nodeElementToLand = isTextElement ? element.parent() : element,
227 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
228 currentTextElement = this.getCurrentTextElement(),
229 currentNodeElement = this.getCurrentNodeElement();
231 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
232 this.wrapper.find('.current-text-element').removeClass('current-text-element');
234 if(textElementToLand) {
235 _markAsCurrent(textElementToLand);
236 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
237 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
238 if(!(textElementToLand.sameNode(currentTextElement)))
239 this.publisher('currentTextElementSet', textElementToLand);
241 document.getSelection().removeAllRanges();
244 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
245 _markAsCurrent(nodeElementToLand);
247 this.publisher('currentNodeElementSet', nodeElementToLand);
251 _moveCaretToTextElement: function(element, where) {
252 var range = document.createRange(),
253 node = element.dom().contents()[0];
255 if(typeof where !== 'number') {
256 range.selectNodeContents(node);
258 range.setStart(node, where);
261 var collapseArg = true;
264 range.collapse(collapseArg);
266 var selection = document.getSelection();
268 selection.removeAllRanges();
269 selection.addRange(range);
270 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
273 setCursorPosition: function(position) {
275 this._moveCaretToTextElement(position.element, position.offset);
279 $.extend(Canvas.prototype.list, {
280 create: function(params) {
281 if(!(params.element1.parent().sameNode(params.element2.parent())))
284 var parent = params.element1.parent();
286 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
287 var tmp = params.element1;
288 params.element1 = params.element2;
289 params.element2 = tmp;
292 var elementsToWrap = [];
294 var place = 'before';
296 parent.children().some(function(element) {
298 if(element.sameNode(params.element1))
300 if(place === 'inside') {
301 if(element instanceof documentElement.DocumentTextElement) {
302 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
303 if(element.children()[0].sameNode(params.element1))
304 params.element1 = element;
306 element.setWlxmlClass('item');
307 elementsToWrap.push(element);
309 if(_e.sameNode(params.element2))
313 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
316 if(parent.is('list')) {
317 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
318 toret = listElement.parent();
323 params.element1.before(toret);
325 elementsToWrap.forEach(function(element) {
327 listElement.append(element);
330 extractItems: function(params) {
331 params = _.extend({merge: true}, params);
332 var list = params.element1.parent();
333 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
336 var idx1 = list.childIndex(params.element1),
337 idx2 = list.childIndex(params.element2),
340 succeedingItems = [],
341 items = list.children(),
342 listIsNested = list.parent().getWlxmlClass() === 'item',
346 var tmp = idx1; idx1 = idx2; idx2 = tmp;
349 items.forEach(function(item, idx) {
351 precedingItems.push(item);
352 else if(idx >= idx1 && idx <= idx2) {
353 extractedItems.push(item);
356 succeedingItems.push(item);
360 var reference = listIsNested ? list.parent() : list;
361 if(succeedingItems.length === 0) {
362 var reference_orig = reference;
363 extractedItems.forEach(function(item) {
364 reference.after(item);
367 item.setWlxmlClass(null);
369 if(precedingItems.length === 0)
370 reference_orig.detach();
371 } else if(precedingItems.length === 0) {
372 extractedItems.forEach(function(item) {
373 reference.before(item);
375 item.setWlxmlClass(null);
378 extractedItems.forEach(function(item) {
379 reference.after(item);
381 item.setWlxmlClass(null);
384 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
388 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
390 succeedingItems.forEach(function(item) {
391 secondList.append(item);
394 reference.after(toAdd);
396 if(!params.merge && listIsNested) {
397 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
401 areItemsOfTheSameList: function(params) {
402 var e1 = params.element1,
403 e2 = params.element2;
404 return e1.parent().sameNode(e2.parent())
405 && e1.parent().is('list');
410 var Cursor = function(canvas) {
411 this.canvas = canvas;
414 $.extend(Cursor.prototype, {
415 isSelecting: function() {
416 var selection = window.getSelection();
417 return !selection.isCollapsed;
419 isSelectingWithinElement: function() {
420 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
422 isSelectingSiblings: function() {
423 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
425 getPosition: function() {
426 return this.getSelectionAnchor();
428 getSelectionStart: function() {
429 return this.getSelectionBoundry('start');
431 getSelectionEnd: function() {
432 return this.getSelectionBoundry('end');
434 getSelectionAnchor: function() {
435 return this.getSelectionBoundry('anchor');
437 getSelectionFocus: function() {
438 return this.getSelectionBoundry('focus');
440 getSelectionBoundry: function(which) {
441 var selection = window.getSelection(),
442 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
443 focusElement = this.canvas.getDocumentElement(selection.focusNode);
445 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
448 if(which === 'anchor') {
450 element: anchorElement,
451 offset: selection.anchorOffset,
452 offsetAtBeginning: selection.anchorOffset === 0,
453 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
456 if(which === 'focus') {
458 element: focusElement,
459 offset: selection.focusOffset,
460 offsetAtBeginning: selection.focusOffset === 0,
461 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
468 if(anchorElement.parent().sameNode(focusElement.parent())) {
469 var parent = anchorElement.parent(),
470 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
472 if(which === 'start') {
473 element = anchorElement;
474 offset = selection.anchorOffset;
476 else if(which === 'end') {
477 element = focusElement,
478 offset = selection.focusOffset;
481 if(which === 'start') {
482 element = focusElement,
483 offset = selection.focusOffset
485 else if(which === 'end') {
486 element = anchorElement;
487 offset = selection.anchorOffset;
491 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
492 if(which === 'start') {
493 element = anchorElement;
494 offset = selection.anchorOffset
496 element = focusElement;
497 offset = selection.focusOffset
504 offsetAtBeginning: offset === 0,
505 offsetAtEnd: element.getText().length === offset
511 fromXML: function(xml, publisher) {
512 return new Canvas(xml, publisher);