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.isNew) {
17 nodeParent = insertion.ofNode.parent();
19 returned = implementation.call(this, insertion.ofNode);
20 if(!options.silent && returned.sameNode(insertion.ofNode)) {
21 this.triggerChangeEvent(insertion.insertsNew ? 'nodeAdded' : 'nodeMoved', {node: insertion.ofNode}, nodeParent, nodeWasContained);
28 var documentNodeTransformations = {
30 var parent = this.parent(),
31 existed = this.document.containsNode(this);
34 this.triggerChangeEvent('nodeDetached', {parent: parent});
36 // This was the root of the document
37 this.document._defineDocumentProperties(null);
43 replaceWith: function(node) {
46 return this.document.replaceRoot(node);
49 toret = this.after(node);
53 throw new Error('Cannot replace node without a parent.');
56 after: INSERTION(function(node) {
57 var next = this.next();
58 if(next && next.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
59 next.setText(node.getText() + next.getText());
63 this._$.after(node.nativeNode);
67 before: INSERTION(function(node) {
68 var prev = this.prev();
69 if(prev && prev.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
70 prev.setText(prev.getText() + node.getText());
74 this._$.before(node.nativeNode);
78 wrapWith: function(node) {
79 var insertion = this.getNodeInsertion(node);
81 if(this.parent() || this.isRoot()) {
82 this.replaceWith(insertion.ofNode);
84 insertion.ofNode.append(this);
85 return insertion.ofNode;
89 * Removes parent of a node if node has no siblings.
95 var parent = this.parent(),
97 if(parent.contents().length === 1) {
98 grandParent = parent.parent();
99 parent.unwrapContent();
105 var elementNodeTransformations = {
109 if(this.parent() && this.isSurroundedByTextElements()) {
111 this.prev().appendText(next.getText());
114 return this.__super__.detach();
117 setTag: function(tagName) {
118 var node = this.document.createDocumentNode({tagName: tagName}),
119 oldTagName = this.getTagName(),
120 myContents = this._$.contents();
122 this.getAttrs().forEach(function(attribute) {
123 node.setAttr(attribute.name, attribute.value, true);
125 node.setData(this.getData());
127 if(this.sameNode(this.document.root)) {
128 this.document._defineDocumentProperties(node._$);
131 /* TODO: This invalidates old references to this node. Caching instances on nodes would fix this. */
132 this._$.replaceWith(node._$);
133 this._setNativeNode(node._$[0]);
134 this._$.append(myContents);
135 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
139 setAttr: function(name, value, silent) {
140 var oldVal = this.getAttr(name);
141 this._$.attr(name, value);
143 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
147 append: INSERTION(function(node) {
148 var last = _.last(this.contents());
149 if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
150 last.setText(last.getText() + node.getText());
154 this._$.append(node.nativeNode);
159 prepend: INSERTION(function(node) {
160 var first = this.contents()[0];
161 if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
162 first.setText(node.getText() + first.getText());
166 this._$.prepend(node.nativeNode);
171 insertAtIndex: function(nativeNode, index) {
172 var contents = this.contents();
173 if(index < contents.length) {
174 return contents[index].before(nativeNode);
175 } else if(index === contents.length) {
176 return this.append(nativeNode);
180 unwrapContent: function() {
181 var parent = this.parent();
186 var myContents = this.contents(),
187 myIdx = parent.indexOf(this);
190 if(myContents.length === 0) {
191 return this.detach();
195 var childrenLength = this.contents().length,
198 this.contents().forEach(function(child) {
199 var returned = this.before(child);
200 if(first && !(returned.sameNode(child))) {
209 element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
210 element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
214 wrapText: function(params) {
215 return this.document._wrapText(_.extend({inside: this}, params));
219 var textNodeTransformations = {
221 impl: function(t, text) {
222 t.oldText = this.getText();
223 this.nativeNode.data = text;
224 this.triggerTextChangeEvent();
227 this.setText(t.oldText);
231 before: INSERTION(function(node) {
232 if(node.nodeType === Node.TEXT_NODE) {
233 this.prependText(node.getText());
237 return this.__super__.before(node, {silent:true});
241 after: INSERTION(function(node) {
242 if(node.nodeType === Node.TEXT_NODE) {
243 this.appendText(node.getText());
247 return this.__super__.after(node, {silent:true});
251 append: function(node) {
252 if(node.nodeType === Node.TEXT_NODE) {
253 this.appendText(node.getText());
258 prepend: function(node) {
259 if(node.nodeType === Node.TEXT_NODE) {
260 this.prependText(node.getText());
266 appendText: function(text) {
267 this.nativeNode.data = this.nativeNode.data + text;
268 this.triggerTextChangeEvent();
271 prependText: function(text) {
272 this.nativeNode.data = text + this.nativeNode.data;
273 this.triggerTextChangeEvent();
276 wrapWith: function(desc) {
277 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
278 return this.document._wrapText({
279 inside: this.parent(),
280 textNodeIdx: this.parent().indexOf(this),
281 offsetStart: Math.min(desc.start, desc.end),
282 offsetEnd: Math.max(desc.start, desc.end),
283 _with: {tagName: desc.tagName, attrs: desc.attrs}
286 return this.__super__.wrapWith.call(this, desc);
290 split: function(params) {
291 var parentElement = this.parent(),
293 succeedingChildren = [],
294 prefix = this.getText().substr(0, params.offset),
295 suffix = this.getText().substr(params.offset);
297 parentElement.contents().forEach(function(child) {
299 succeedingChildren.push(child);
301 if(child.sameNode(this)) {
306 if(prefix.length > 0) {
307 this.setText(prefix);
314 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
315 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
316 parentElement.after(newElement);
318 if(suffix.length > 0) {
319 newElement.append({text: suffix});
321 succeedingChildren.forEach(function(child) {
322 newElement.append(child);
325 return {first: parentElement, second: newElement};
328 divideWithElementNode: function(node, params) {
329 var insertion = this.getNodeInsertion(node),
330 myText = this.getText();
332 if(params.offset === myText.length) {
333 return this.after(node);
335 if(params.offset === 0) {
336 return this.before(node);
339 var lhsText = myText.substr(0, params.offset),
340 rhsText = myText.substr(params.offset),
341 rhsTextNode = this.document.createDocumentNode({text: rhsText});
343 this.setText(lhsText);
344 this.after(insertion.ofNode);
345 insertion.ofNode.after(rhsTextNode);
346 return insertion.ofNode;
350 var documentTransformations = {
351 wrapNodes: function(params) {
352 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
353 throw new Error('Wrapping non-sibling nodes not supported.');
356 var parent = params.node1.parent(),
357 parentContents = parent.contents(),
358 wrapper = this.createDocumentNode({
359 tagName: params._with.tagName,
360 attrs: params._with.attrs}),
361 idx1 = parent.indexOf(params.node1),
362 idx2 = parent.indexOf(params.node2);
370 var insertingMethod, insertingTarget;
372 insertingMethod = 'prepend';
373 insertingTarget = parent;
375 insertingMethod = 'after';
376 insertingTarget = parentContents[idx1-1];
379 for(var i = idx1; i <= idx2; i++) {
380 wrapper.append(parentContents[i].detach());
383 insertingTarget[insertingMethod](wrapper);
387 _wrapText: function(params) {
388 params = _.extend({textNodeIdx: 0}, params);
389 if(typeof params.textNodeIdx === 'number') {
390 params.textNodeIdx = [params.textNodeIdx];
393 var contentsInside = params.inside.contents(),
394 idx1 = Math.min.apply(Math, params.textNodeIdx),
395 idx2 = Math.max.apply(Math, params.textNodeIdx),
396 textNode1 = contentsInside[idx1],
397 textNode2 = contentsInside[idx2],
398 sameNode = textNode1.sameNode(textNode2),
399 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
400 prefixInside = textNode1.getText().substr(params.offsetStart),
401 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
402 suffixOutside = textNode2.getText().substr(params.offsetEnd)
405 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
406 throw new Error('Wrapping text in non-sibling text nodes not supported.');
409 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
410 textNode1.after(wrapperElement);
413 if(prefixOutside.length > 0) {
414 wrapperElement.before({text:prefixOutside});
417 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
418 wrapperElement.append({text: core});
421 if(prefixInside.length > 0) {
422 wrapperElement.append({text: prefixInside});
424 for(var i = idx1 + 1; i < idx2; i++) {
425 wrapperElement.append(contentsInside[i]);
427 if(suffixInside.length > 0) {
428 wrapperElement.append({text: suffixInside});
431 if(suffixOutside.length > 0) {
432 wrapperElement.after({text: suffixOutside});
434 return wrapperElement;
436 replaceRoot: function(node) {
437 var insertion = this.getNodeInsertion(node);
439 this._defineDocumentProperties(insertion.ofNode._$);
440 insertion.ofNode.triggerChangeEvent('nodeAdded');
441 return insertion.ofNode;
443 deleteText: function(params) {
444 var ptr, next, toDetach, middle, text;
446 if(params.from.node.sameNode(params.to.node)) {
447 ptr = params.from.node;
448 text = ptr.getText();
449 ptr.setText(text.substr(0, params.from.offset) + text.substr(params.to.offset));
453 // Both edge text nodes need to be edited before anything else happen in case that
454 // they get merged when detaching content between them.
455 params.from.node.setText(params.from.node.getText().substr(0, params.from.offset));
456 params.to.node.setText(params.to.node.getText().substr(params.to.offset));
458 ptr = params.from.node;
461 while(next || ptr.parent()) {
463 if(next.sameNode(params.to.node)) {
466 else if(next.nodeType === Node.ELEMENT_NODE && next.containsNode(params.to.node)) {
480 if(!this.containsNode(params.to.node)) {
481 // The end node was merged during detaching nodes above - there is nothing more left to do.
485 ptr = middle.contents()[0];
486 while(ptr && !ptr.sameNode(params.to.node)) {
487 if(ptr.nodeType === Node.ELEMENT_NODE && ptr.containsNode(params.to.node)) {
488 ptr = ptr.contents()[0];
500 transformations: documentTransformations
503 transformations: documentNodeTransformations
506 transformations: elementNodeTransformations
509 transformations: textNodeTransformations