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.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) {
66 var next = this.next();
67 if(next && next.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
68 next.setText(node.getText() + next.getText());
72 this._$.after(node.nativeNode);
76 before: INSERTION(function(node) {
77 var prev = this.prev();
78 if(prev && prev.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
79 prev.setText(prev.getText() + node.getText());
83 this._$.before(node.nativeNode);
87 wrapWith: function(node) {
88 var insertion = this.getNodeInsertion(node);
90 if(this.parent() || this.isRoot()) {
91 this.replaceWith(insertion.ofNode);
93 insertion.ofNode.append(this);
94 return insertion.ofNode;
98 * Removes parent of a node if node has no siblings.
104 var parent = this.parent(),
106 if(parent.contents().length === 1) {
107 grandParent = parent.parent();
108 parent.unwrapContent();
114 var elementNodeTransformations = {
118 if(this.parent() && this.isSurroundedByTextNodes()) {
120 this.prev().appendText(next.getText());
123 return this.__super__.detach();
126 setTag: function(tagName) {
127 var node = this.document.createDocumentNode({tagName: tagName});
129 this.getAttrs().forEach(function(attribute) {
130 node.setAttr(attribute.name, attribute.value);
133 this.contents().forEach(function(child) {
137 node.setData(this.getData());
139 this.replaceWith(node);
143 setAttr: function(name, value, silent) {
144 var oldVal = this.getAttr(name);
145 this._$.attr(name, value);
147 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
151 append: INSERTION(function(node) {
152 var last = _.last(this.contents());
153 if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
154 last.setText(last.getText() + node.getText());
158 this._$.append(node.nativeNode);
163 prepend: INSERTION(function(node) {
164 var first = this.contents()[0];
165 if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
166 first.setText(node.getText() + first.getText());
170 this._$.prepend(node.nativeNode);
175 insertAtIndex: function(nativeNode, index) {
176 var contents = this.contents();
177 if(index < contents.length) {
178 return contents[index].before(nativeNode);
179 } else if(index === contents.length) {
180 return this.append(nativeNode);
184 unwrapContent: function() {
185 var parent = this.parent();
190 var myContents = this.contents(),
191 myIdx = parent.indexOf(this);
194 if(myContents.length === 0) {
195 return this.detach();
199 var childrenLength = this.contents().length,
202 this.contents().forEach(function(child) {
203 var returned = this.before(child);
204 if(first && !(returned.sameNode(child))) {
213 element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
214 element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
218 wrapText: function(params) {
219 return this.document._wrapText(_.extend({inside: this}, params));
223 var textNodeTransformations = {
225 impl: function(t, text) {
226 t.oldText = this.getText();
227 this.nativeNode.data = text;
228 this.triggerTextChangeEvent();
231 this.setText(t.oldText);
235 before: INSERTION(function(node) {
236 if(node.nodeType === Node.TEXT_NODE) {
237 this.prependText(node.getText());
241 return this.__super__.before(node, {silent:true});
245 after: INSERTION(function(node) {
246 if(node.nodeType === Node.TEXT_NODE) {
247 this.appendText(node.getText());
251 return this.__super__.after(node, {silent:true});
255 append: function(node) {
256 if(node.nodeType === Node.TEXT_NODE) {
257 this.appendText(node.getText());
262 prepend: function(node) {
263 if(node.nodeType === Node.TEXT_NODE) {
264 this.prependText(node.getText());
270 appendText: function(text) {
271 this.nativeNode.data = this.nativeNode.data + text;
272 this.triggerTextChangeEvent();
275 prependText: function(text) {
276 this.nativeNode.data = text + this.nativeNode.data;
277 this.triggerTextChangeEvent();
280 wrapWith: function(desc) {
281 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
282 return this.document._wrapText({
283 inside: this.parent(),
284 textNodeIdx: this.parent().indexOf(this),
285 offsetStart: Math.min(desc.start, desc.end),
286 offsetEnd: Math.max(desc.start, desc.end),
287 _with: {tagName: desc.tagName, attrs: desc.attrs}
290 return this.__super__.wrapWith.call(this, desc);
294 split: function(params) {
295 var parentElement = this.parent(),
297 succeedingChildren = [],
298 prefix = this.getText().substr(0, params.offset),
299 suffix = this.getText().substr(params.offset);
301 parentElement.contents().forEach(function(child) {
303 succeedingChildren.push(child);
305 if(child.sameNode(this)) {
310 if(prefix.length > 0) {
311 this.setText(prefix);
318 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
319 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
320 parentElement.after(newElement);
322 succeedingChildren.reverse().forEach(function(child) {
323 newElement.prepend(child);
325 if(suffix.length > 0) {
326 newElement.prepend({text: suffix});
329 return {first: parentElement, second: newElement};
332 divideWithElementNode: function(node, params) {
333 var insertion = this.getNodeInsertion(node),
334 myText = this.getText();
336 if(params.offset === myText.length) {
337 return this.after(node);
339 if(params.offset === 0) {
340 return this.before(node);
343 var lhsText = myText.substr(0, params.offset),
344 rhsText = myText.substr(params.offset),
345 rhsTextNode = this.document.createDocumentNode({text: rhsText});
347 this.setText(lhsText);
348 this.after(insertion.ofNode);
349 insertion.ofNode.after(rhsTextNode);
350 return insertion.ofNode;
354 var documentTransformations = {
355 wrapNodes: function(params) {
356 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
357 throw new Error('Wrapping non-sibling nodes not supported.');
360 var parent = params.node1.parent(),
361 parentContents = parent.contents(),
362 wrapper = this.createDocumentNode({
363 tagName: params._with.tagName,
364 attrs: params._with.attrs}),
365 idx1 = parent.indexOf(params.node1),
366 idx2 = parent.indexOf(params.node2);
374 var insertingMethod, insertingTarget;
376 insertingMethod = 'prepend';
377 insertingTarget = parent;
379 insertingMethod = 'after';
380 insertingTarget = parentContents[idx1-1];
383 for(var i = idx1; i <= idx2; i++) {
384 wrapper.append(parentContents[i].detach());
387 insertingTarget[insertingMethod](wrapper);
391 _wrapText: function(params) {
392 params = _.extend({textNodeIdx: 0}, params);
393 if(typeof params.textNodeIdx === 'number') {
394 params.textNodeIdx = [params.textNodeIdx];
397 var contentsInside = params.inside.contents(),
398 idx1 = Math.min.apply(Math, params.textNodeIdx),
399 idx2 = Math.max.apply(Math, params.textNodeIdx),
400 textNode1 = contentsInside[idx1],
401 textNode2 = contentsInside[idx2],
402 sameNode = textNode1.sameNode(textNode2),
403 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
404 prefixInside = textNode1.getText().substr(params.offsetStart),
405 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
406 suffixOutside = textNode2.getText().substr(params.offsetEnd)
409 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
410 throw new Error('Wrapping text in non-sibling text nodes not supported.');
413 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
414 textNode1.after(wrapperElement);
417 if(prefixOutside.length > 0) {
418 wrapperElement.before({text:prefixOutside});
421 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
422 wrapperElement.append({text: core});
425 if(prefixInside.length > 0) {
426 wrapperElement.append({text: prefixInside});
428 for(var i = idx1 + 1; i < idx2; i++) {
429 wrapperElement.append(contentsInside[i]);
431 if(suffixInside.length > 0) {
432 wrapperElement.append({text: suffixInside});
435 if(suffixOutside.length > 0) {
436 wrapperElement.after({text: suffixOutside});
438 return wrapperElement;
440 replaceRoot: function(node) {
441 var insertion = this.getNodeInsertion(node);
443 this._defineDocumentProperties(insertion.ofNode._$);
444 insertion.ofNode.triggerChangeEvent('nodeAdded');
445 return insertion.ofNode;
447 deleteText: function(params) {
448 var ptr, next, toDetach, middle, text;
450 if(params.from.node.sameNode(params.to.node)) {
451 ptr = params.from.node;
452 text = ptr.getText();
453 ptr.setText(text.substr(0, params.from.offset) + text.substr(params.to.offset));
457 // Both edge text nodes need to be edited before anything else happen in case that
458 // they get merged when detaching content between them.
459 params.from.node.setText(params.from.node.getText().substr(0, params.from.offset));
460 params.to.node.setText(params.to.node.getText().substr(params.to.offset));
462 ptr = params.from.node;
465 while(next || ptr.parent()) {
467 if(next.sameNode(params.to.node)) {
470 else if(next.nodeType === Node.ELEMENT_NODE && next.containsNode(params.to.node)) {
484 if(!this.containsNode(params.to.node)) {
485 // The end node was merged during detaching nodes above - there is nothing more left to do.
489 ptr = middle.contents()[0];
490 while(ptr && !ptr.sameNode(params.to.node)) {
491 if(ptr.nodeType === Node.ELEMENT_NODE && ptr.containsNode(params.to.node)) {
492 ptr = ptr.contents()[0];
504 transformations: documentTransformations
507 transformations: documentNodeTransformations
510 transformations: elementNodeTransformations
513 transformations: textNodeTransformations