1 define(function(require) {
6 var _ = require('libs/underscore');
9 var INSERTION = function(implementation) {
10 var toret = function(node, options) {
11 var insertion = this.getNodeInsertion(node),
12 nodeWasContained = this.document.containsNode(insertion.ofNode),
15 options = options || {};
16 if(!(this.document.containsNode(this)) || !insertion.insertsNew) {
17 nodeParent = insertion.ofNode.parent();
19 if(!insertion.insertsNew && insertion.ofNode.isSurroundedByTextNodes()) {
20 var prev = insertion.ofNode.prev(),
21 next = insertion.ofNode.next();
22 prev.setText(prev.getText()+next.getText());
25 returned = implementation.call(this, insertion.ofNode);
26 if(!options.silent && returned && returned.sameNode(insertion.ofNode)) {
27 if(!insertion.insertsNew) {
28 this.triggerChangeEvent('nodeDetached', {node: insertion.ofNode, parent: nodeParent, move: true});
30 this.triggerChangeEvent('nodeAdded', {node: insertion.ofNode, move: !insertion.insertsNew}, nodeParent, nodeWasContained);
37 var documentNodeTransformations = {
39 var parent = this.parent(),
40 existed = this.document.containsNode(this);
43 this.triggerChangeEvent('nodeDetached', {parent: parent});
45 // This was the root of the document
46 this.document._defineDocumentProperties(null);
52 replaceWith: function(node) {
55 return this.document.replaceRoot(node);
58 toret = this.after(node);
62 throw new Error('Cannot replace node without a parent.');
65 after: INSERTION(function(node) {
69 var next = this.next();
71 if(next && next.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
72 next.setText(node.getText() + next.getText());
76 this._$.after(node.nativeNode);
80 before: INSERTION(function(node) {
84 var prev = this.prev();
85 if(prev && prev.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
86 prev.setText(prev.getText() + node.getText());
90 this._$.before(node.nativeNode);
94 wrapWith: function(node) {
95 var insertion = this.getNodeInsertion(node);
97 if(this.parent() || this.isRoot()) {
98 this.replaceWith(insertion.ofNode);
100 insertion.ofNode.append(this);
101 return insertion.ofNode;
105 * Removes parent of a node if node has no siblings.
111 var parent = this.parent(),
113 if(parent.contents().length === 1) {
114 grandParent = parent.parent();
115 parent.unwrapContent();
121 var elementNodeTransformations = {
123 detach: function(params) {
126 params = params || {};
128 if(!params.normalizeStrategy) {
129 params.normalizeStrategy = 'merge';
132 if(this.parent() && this.isSurroundedByTextNodes()) {
133 if(params.normalizeStrategy === 'detach-left') {
134 this.prev().detach();
135 } else if(params.normalizeStrategy === 'detach-right') {
136 this.next().detach();
137 } else if(params.normalizeStrategy === 'merge') {
142 previousLen: prev.getText().length
144 prev.appendText(next.getText());
147 throw new Error('unknown normalize strategy for detach');
150 return this.__super__.detach();
153 setTag: function(tagName) {
154 var node = this.document.createDocumentNode({tagName: tagName});
156 this.getAttrs().forEach(function(attribute) {
157 node.setAttr(attribute.name, attribute.value);
160 this.contents().forEach(function(child) {
164 node.setData(this.getData());
166 this.replaceWith(node);
170 setAttr: function(name, value, silent) {
171 var oldVal = this.getAttr(name);
172 this._$.attr(name, value);
174 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
178 append: INSERTION(function(node) {
179 var last = _.last(this.contents());
180 if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
181 last.setText(last.getText() + node.getText());
185 this._$.append(node.nativeNode);
190 prepend: INSERTION(function(node) {
191 var first = this.contents()[0];
192 if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
193 first.setText(node.getText() + first.getText());
197 this._$.prepend(node.nativeNode);
202 insertAtIndex: function(nativeNode, index) {
203 var contents = this.contents();
204 if(index < contents.length) {
205 return contents[index].before(nativeNode);
206 } else if(index === contents.length) {
207 return this.append(nativeNode);
211 unwrapContent: function() {
212 var parent = this.parent();
218 .filter(function(child) {
219 return child.getProperty('describesParent');
221 .forEach(function(child) {
225 var myContents = this.contents(),
226 myIdx = parent.indexOf(this);
228 if(myContents.length === 0) {
229 return this.detach();
232 var childrenLength = this.contents().length,
235 this.contents().forEach(function(child) {
236 var returned = this.before(child);
237 if(first && !(returned.sameNode(child))) {
246 element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
247 element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
251 wrapText: function(params) {
252 return this.document._wrapText(_.extend({inside: this}, params));
256 var textNodeTransformations = {
258 impl: function(t, text) {
259 t.oldText = this.getText();
260 this.nativeNode.data = text;
261 this.triggerTextChangeEvent();
264 this.setText(t.oldText);
268 before: INSERTION(function(node) {
269 if(node.nodeType === Node.TEXT_NODE) {
270 this.prependText(node.getText());
274 return this.__super__.before(node, {silent:true});
278 after: INSERTION(function(node) {
279 if(node.nodeType === Node.TEXT_NODE) {
280 this.appendText(node.getText());
284 return this.__super__.after(node, {silent:true});
288 append: function(node) {
289 if(node.nodeType === Node.TEXT_NODE) {
290 this.appendText(node.getText());
295 prepend: function(node) {
296 if(node.nodeType === Node.TEXT_NODE) {
297 this.prependText(node.getText());
303 appendText: function(text) {
304 this.nativeNode.data = this.nativeNode.data + text;
305 this.triggerTextChangeEvent();
308 prependText: function(text) {
309 this.nativeNode.data = text + this.nativeNode.data;
310 this.triggerTextChangeEvent();
313 wrapWith: function(desc) {
314 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
315 return this.document._wrapText({
316 inside: this.parent(),
317 textNodeIdx: this.parent().indexOf(this),
318 offsetStart: Math.min(desc.start, desc.end),
319 offsetEnd: Math.max(desc.start, desc.end),
320 _with: {tagName: desc.tagName, attrs: desc.attrs}
323 return this.__super__.wrapWith.call(this, desc);
327 split: function(params) {
328 var parentElement = this.parent(),
330 succeedingChildren = [],
331 prefix = this.getText().substr(0, params.offset),
332 suffix = this.getText().substr(params.offset);
334 parentElement.contents().forEach(function(child) {
336 succeedingChildren.push(child);
338 if(child.sameNode(this)) {
343 if(prefix.length > 0) {
344 this.setText(prefix);
351 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
352 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
353 parentElement.after(newElement);
355 succeedingChildren.reverse().forEach(function(child) {
356 newElement.prepend(child);
358 if(suffix.length > 0) {
359 newElement.prepend({text: suffix});
362 return {first: parentElement, second: newElement, created: newElement};
365 divideWithElementNode: function(node, params) {
366 var insertion = this.getNodeInsertion(node),
367 myText = this.getText();
369 if(params.offset === myText.length) {
370 return this.after(node);
372 if(params.offset === 0) {
373 return this.before(node);
376 var lhsText = myText.substr(0, params.offset),
377 rhsText = myText.substr(params.offset),
378 rhsTextNode = this.document.createDocumentNode({text: rhsText});
380 this.setText(lhsText);
381 this.after(insertion.ofNode);
382 insertion.ofNode.after(rhsTextNode);
383 return insertion.ofNode;
387 var documentTransformations = {
388 wrapNodes: function(params) {
389 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
390 throw new Error('Wrapping non-sibling nodes not supported.');
393 var parent = params.node1.parent(),
394 parentContents = parent.contents(),
395 wrapper = this.createDocumentNode({
396 tagName: params._with.tagName,
397 attrs: params._with.attrs}),
398 idx1 = parent.indexOf(params.node1),
399 idx2 = parent.indexOf(params.node2);
407 var insertingMethod, insertingTarget;
409 insertingMethod = 'prepend';
410 insertingTarget = parent;
412 insertingMethod = 'after';
413 insertingTarget = parentContents[idx1-1];
416 for(var i = idx1; i <= idx2; i++) {
417 if(!parentContents[i].getProperty('describesParent')) {
418 wrapper.append(parentContents[i].detach());
422 insertingTarget[insertingMethod](wrapper);
426 _wrapText: function(params) {
427 params = _.extend({textNodeIdx: 0}, params);
428 if(typeof params.textNodeIdx === 'number') {
429 params.textNodeIdx = [params.textNodeIdx];
432 var contentsInside = params.inside.contents(),
433 idx1 = Math.min.apply(Math, params.textNodeIdx),
434 idx2 = Math.max.apply(Math, params.textNodeIdx),
435 textNode1 = contentsInside[idx1],
436 textNode2 = contentsInside[idx2],
437 sameNode = textNode1.sameNode(textNode2),
438 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
439 prefixInside = textNode1.getText().substr(params.offsetStart),
440 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
441 suffixOutside = textNode2.getText().substr(params.offsetEnd)
444 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
445 throw new Error('Wrapping text in non-sibling text nodes not supported.');
448 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
449 textNode1.after(wrapperElement);
452 if(prefixOutside.length > 0) {
453 wrapperElement.before({text:prefixOutside});
456 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
457 wrapperElement.append({text: core});
460 if(prefixInside.length > 0) {
461 wrapperElement.append({text: prefixInside});
463 for(var i = idx1 + 1; i < idx2; i++) {
464 if(!contentsInside[i].getProperty('describesParent')) {
465 wrapperElement.append(contentsInside[i]);
468 if(suffixInside.length > 0) {
469 wrapperElement.append({text: suffixInside});
472 if(suffixOutside.length > 0) {
473 wrapperElement.after({text: suffixOutside});
475 return wrapperElement;
477 replaceRoot: function(node) {
478 var insertion = this.getNodeInsertion(node);
480 this._defineDocumentProperties(insertion.ofNode._$);
481 insertion.ofNode.triggerChangeEvent('nodeAdded');
482 return insertion.ofNode;
484 deleteText: function(params) {
485 var ptr, next, nextNext, toDetach, middle, text;
487 if(params.from.node.sameNode(params.to.node)) {
488 ptr = params.from.node;
489 text = ptr.getText();
490 ptr.setText(text.substr(0, params.from.offset) + text.substr(params.to.offset));
494 // Both edge text nodes need to be edited before anything else happen in case that
495 // they get merged when detaching content between them.
496 params.from.node.setText(params.from.node.getText().substr(0, params.from.offset));
497 params.to.node.setText(params.to.node.getText().substr(params.to.offset));
499 ptr = params.from.node;
502 while(next || ptr.parent()) {
504 if(next.sameNode(params.to.node)) {
507 else if(next.nodeType === Node.ELEMENT_NODE && next.containsNode(params.to.node)) {
513 nextNext = next ? next.next() : null;
514 toDetach.detach({normalizeStrategy: (next && next.sameNode(params.to.node)) ? 'merge' : 'detach-right'});
515 if(next && !next.isInDocument()) {
525 if(!this.containsNode(params.to.node)) {
526 // The end node was merged during detaching nodes above - there is nothing more left to do.
530 ptr = middle.contents()[0];
531 while(ptr && !ptr.sameNode(params.to.node)) {
532 if(ptr.nodeType === Node.ELEMENT_NODE && ptr.containsNode(params.to.node)) {
533 ptr = ptr.contents()[0];
545 transformations: documentTransformations
548 transformations: documentNodeTransformations
551 transformations: elementNodeTransformations
554 transformations: textNodeTransformations