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 this.before(insertion.ofNode);
83 insertion.ofNode.append(this);
84 return insertion.ofNode;
88 * Removes parent of a node if node has no siblings.
94 var parent = this.parent(),
96 if(parent.contents().length === 1) {
97 grandParent = parent.parent();
98 parent.unwrapContent();
104 var elementNodeTransformations = {
108 if(this.parent() && this.isSurroundedByTextElements()) {
110 this.prev().appendText(next.getText());
113 return this.__super__.detach();
116 setTag: function(tagName) {
117 var node = this.document.createDocumentNode({tagName: tagName}),
118 oldTagName = this.getTagName(),
119 myContents = this._$.contents();
121 this.getAttrs().forEach(function(attribute) {
122 node.setAttr(attribute.name, attribute.value, true);
124 node.setData(this.getData());
126 if(this.sameNode(this.document.root)) {
127 this.document._defineDocumentProperties(node._$);
130 /* TODO: This invalidates old references to this node. Caching instances on nodes would fix this. */
131 this._$.replaceWith(node._$);
132 this._setNativeNode(node._$[0]);
133 this._$.append(myContents);
134 this.triggerChangeEvent('nodeTagChange', {oldTagName: oldTagName, newTagName: this.getTagName()});
138 setAttr: function(name, value, silent) {
139 var oldVal = this.getAttr(name);
140 this._$.attr(name, value);
142 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
146 append: INSERTION(function(node) {
147 var last = _.last(this.contents());
148 if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
149 last.setText(last.getText() + node.getText());
153 this._$.append(node.nativeNode);
158 prepend: INSERTION(function(node) {
159 var first = this.contents()[0];
160 if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
161 first.setText(node.getText() + first.getText());
165 this._$.prepend(node.nativeNode);
170 insertAtIndex: function(nativeNode, index) {
171 var contents = this.contents();
172 if(index < contents.length) {
173 return contents[index].before(nativeNode);
174 } else if(index === contents.length) {
175 return this.append(nativeNode);
179 unwrapContent: function() {
180 var parent = this.parent();
185 var myContents = this.contents(),
186 myIdx = parent.indexOf(this);
189 if(myContents.length === 0) {
190 return this.detach();
194 var childrenLength = this.contents().length,
197 this.contents().forEach(function(child) {
198 var returned = this.before(child);
199 if(first && !(returned.sameNode(child))) {
208 element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
209 element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
213 wrapText: function(params) {
214 return this.document._wrapText(_.extend({inside: this}, params));
218 var textNodeTransformations = {
220 impl: function(t, text) {
221 t.oldText = this.getText();
222 this.nativeNode.data = text;
223 this.triggerTextChangeEvent();
226 this.setText(t.oldText);
230 before: INSERTION(function(node) {
231 if(node.nodeType === Node.TEXT_NODE) {
232 this.prependText(node.getText());
236 return this.__super__.before(node, {silent:true});
240 after: INSERTION(function(node) {
241 if(node.nodeType === Node.TEXT_NODE) {
242 this.appendText(node.getText());
246 return this.__super__.after(node, {silent:true});
250 append: function(node) {
251 if(node.nodeType === Node.TEXT_NODE) {
252 this.appendText(node.getText());
257 prepend: function(node) {
258 if(node.nodeType === Node.TEXT_NODE) {
259 this.prependText(node.getText());
265 appendText: function(text) {
266 this.nativeNode.data = this.nativeNode.data + text;
267 this.triggerTextChangeEvent();
270 prependText: function(text) {
271 this.nativeNode.data = text + this.nativeNode.data;
272 this.triggerTextChangeEvent();
275 wrapWith: function(desc) {
276 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
277 return this.document._wrapText({
278 inside: this.parent(),
279 textNodeIdx: this.parent().indexOf(this),
280 offsetStart: Math.min(desc.start, desc.end),
281 offsetEnd: Math.max(desc.start, desc.end),
282 _with: {tagName: desc.tagName, attrs: desc.attrs}
285 return this.__super__.wrapWith.call(this, desc);
289 split: function(params) {
290 var parentElement = this.parent(),
292 succeedingChildren = [],
293 prefix = this.getText().substr(0, params.offset),
294 suffix = this.getText().substr(params.offset);
296 parentElement.contents().forEach(function(child) {
298 succeedingChildren.push(child);
300 if(child.sameNode(this)) {
305 if(prefix.length > 0) {
306 this.setText(prefix);
313 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
314 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
315 parentElement.after(newElement);
317 if(suffix.length > 0) {
318 newElement.append({text: suffix});
320 succeedingChildren.forEach(function(child) {
321 newElement.append(child);
324 return {first: parentElement, second: newElement};
327 divideWithElementNode: function(node, params) {
328 var insertion = this.getNodeInsertion(node),
329 myText = this.getText();
331 if(params.offset === myText.length) {
332 return this.after(node);
334 if(params.offset === 0) {
335 return this.before(node);
338 var lhsText = myText.substr(0, params.offset),
339 rhsText = myText.substr(params.offset),
340 rhsTextNode = this.document.createDocumentNode({text: rhsText});
342 this.setText(lhsText);
343 this.after(insertion.ofNode);
344 insertion.ofNode.after(rhsTextNode);
345 return insertion.ofNode;
349 var documentTransformations = {
350 wrapNodes: function(params) {
351 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
352 throw new Error('Wrapping non-sibling nodes not supported.');
355 var parent = params.node1.parent(),
356 parentContents = parent.contents(),
357 wrapper = this.createDocumentNode({
358 tagName: params._with.tagName,
359 attrs: params._with.attrs}),
360 idx1 = parent.indexOf(params.node1),
361 idx2 = parent.indexOf(params.node2);
369 var insertingMethod, insertingTarget;
371 insertingMethod = 'prepend';
372 insertingTarget = parent;
374 insertingMethod = 'after';
375 insertingTarget = parentContents[idx1-1];
378 for(var i = idx1; i <= idx2; i++) {
379 wrapper.append(parentContents[i].detach());
382 insertingTarget[insertingMethod](wrapper);
386 _wrapText: function(params) {
387 params = _.extend({textNodeIdx: 0}, params);
388 if(typeof params.textNodeIdx === 'number') {
389 params.textNodeIdx = [params.textNodeIdx];
392 var contentsInside = params.inside.contents(),
393 idx1 = Math.min.apply(Math, params.textNodeIdx),
394 idx2 = Math.max.apply(Math, params.textNodeIdx),
395 textNode1 = contentsInside[idx1],
396 textNode2 = contentsInside[idx2],
397 sameNode = textNode1.sameNode(textNode2),
398 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
399 prefixInside = textNode1.getText().substr(params.offsetStart),
400 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
401 suffixOutside = textNode2.getText().substr(params.offsetEnd)
404 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
405 throw new Error('Wrapping text in non-sibling text nodes not supported.');
408 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
409 textNode1.after(wrapperElement);
412 if(prefixOutside.length > 0) {
413 wrapperElement.before({text:prefixOutside});
416 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
417 wrapperElement.append({text: core});
420 if(prefixInside.length > 0) {
421 wrapperElement.append({text: prefixInside});
423 for(var i = idx1 + 1; i < idx2; i++) {
424 wrapperElement.append(contentsInside[i]);
426 if(suffixInside.length > 0) {
427 wrapperElement.append({text: suffixInside});
430 if(suffixOutside.length > 0) {
431 wrapperElement.after({text: suffixOutside});
433 return wrapperElement;
435 replaceRoot: function(node) {
436 var insertion = this.getNodeInsertion(node);
438 this._defineDocumentProperties(insertion.ofNode._$);
439 insertion.ofNode.triggerChangeEvent('nodeAdded');
440 return insertion.ofNode;
442 deleteText: function(params) {
443 var ptr, next, toDetach, middle, text;
445 if(params.from.node.sameNode(params.to.node)) {
446 ptr = params.from.node;
447 text = ptr.getText();
448 ptr.setText(text.substr(0, params.from.offset) + text.substr(params.to.offset));
452 // Both edge text nodes need to be edited before anything else happen in case that
453 // they get merged when detaching content between them.
454 params.from.node.setText(params.from.node.getText().substr(0, params.from.offset));
455 params.to.node.setText(params.to.node.getText().substr(params.to.offset));
457 ptr = params.from.node;
460 while(next || ptr.parent()) {
462 if(next.sameNode(params.to.node)) {
465 else if(next.nodeType === Node.ELEMENT_NODE && next.containsNode(params.to.node)) {
479 if(!this.containsNode(params.to.node)) {
480 // The end node was merged during detaching nodes above - there is nothing more left to do.
484 ptr = middle.contents()[0];
485 while(ptr && !ptr.sameNode(params.to.node)) {
486 if(ptr.nodeType === Node.ELEMENT_NODE && ptr.containsNode(params.to.node)) {
487 ptr = ptr.contents()[0];
499 transformations: documentTransformations
502 transformations: documentNodeTransformations
505 transformations: elementNodeTransformations
508 transformations: textNodeTransformations