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 = {
125 if(this.parent() && this.isSurroundedByTextNodes()) {
127 this.prev().appendText(next.getText());
130 return this.__super__.detach();
133 setTag: function(tagName) {
134 var node = this.document.createDocumentNode({tagName: tagName});
136 this.getAttrs().forEach(function(attribute) {
137 node.setAttr(attribute.name, attribute.value);
140 this.contents().forEach(function(child) {
144 node.setData(this.getData());
146 this.replaceWith(node);
150 setAttr: function(name, value, silent) {
151 var oldVal = this.getAttr(name);
152 this._$.attr(name, value);
154 this.triggerChangeEvent('nodeAttrChange', {attr: name, oldVal: oldVal, newVal: value});
158 append: INSERTION(function(node) {
159 var last = _.last(this.contents());
160 if(last && last.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
161 last.setText(last.getText() + node.getText());
165 this._$.append(node.nativeNode);
170 prepend: INSERTION(function(node) {
171 var first = this.contents()[0];
172 if(first && first.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
173 first.setText(node.getText() + first.getText());
177 this._$.prepend(node.nativeNode);
182 insertAtIndex: function(nativeNode, index) {
183 var contents = this.contents();
184 if(index < contents.length) {
185 return contents[index].before(nativeNode);
186 } else if(index === contents.length) {
187 return this.append(nativeNode);
191 unwrapContent: function() {
192 var parent = this.parent();
198 .filter(function(child) {
199 return child.getProperty('describesParent');
201 .forEach(function(child) {
205 var myContents = this.contents(),
206 myIdx = parent.indexOf(this);
208 if(myContents.length === 0) {
209 return this.detach();
212 var childrenLength = this.contents().length,
215 this.contents().forEach(function(child) {
216 var returned = this.before(child);
217 if(first && !(returned.sameNode(child))) {
226 element1: parent.contents()[myIdx + (shiftRange ? -1 : 0)],
227 element2: parent.contents()[myIdx + childrenLength-1 + (shiftRange ? -1 : 0)]
231 wrapText: function(params) {
232 return this.document._wrapText(_.extend({inside: this}, params));
236 var textNodeTransformations = {
238 impl: function(t, text) {
239 t.oldText = this.getText();
240 this.nativeNode.data = text;
241 this.triggerTextChangeEvent();
244 this.setText(t.oldText);
248 before: INSERTION(function(node) {
249 if(node.nodeType === Node.TEXT_NODE) {
250 this.prependText(node.getText());
254 return this.__super__.before(node, {silent:true});
258 after: INSERTION(function(node) {
259 if(node.nodeType === Node.TEXT_NODE) {
260 this.appendText(node.getText());
264 return this.__super__.after(node, {silent:true});
268 append: function(node) {
269 if(node.nodeType === Node.TEXT_NODE) {
270 this.appendText(node.getText());
275 prepend: function(node) {
276 if(node.nodeType === Node.TEXT_NODE) {
277 this.prependText(node.getText());
283 appendText: function(text) {
284 this.nativeNode.data = this.nativeNode.data + text;
285 this.triggerTextChangeEvent();
288 prependText: function(text) {
289 this.nativeNode.data = text + this.nativeNode.data;
290 this.triggerTextChangeEvent();
293 wrapWith: function(desc) {
294 if(typeof desc.start === 'number' && typeof desc.end === 'number') {
295 return this.document._wrapText({
296 inside: this.parent(),
297 textNodeIdx: this.parent().indexOf(this),
298 offsetStart: Math.min(desc.start, desc.end),
299 offsetEnd: Math.max(desc.start, desc.end),
300 _with: {tagName: desc.tagName, attrs: desc.attrs}
303 return this.__super__.wrapWith.call(this, desc);
307 split: function(params) {
308 var parentElement = this.parent(),
310 succeedingChildren = [],
311 prefix = this.getText().substr(0, params.offset),
312 suffix = this.getText().substr(params.offset);
314 parentElement.contents().forEach(function(child) {
316 succeedingChildren.push(child);
318 if(child.sameNode(this)) {
323 if(prefix.length > 0) {
324 this.setText(prefix);
331 parentElement.getAttrs().forEach(function(attr) {attrs[attr.name] = attr.value; });
332 var newElement = this.document.createDocumentNode({tagName: parentElement.getTagName(), attrs: attrs});
333 parentElement.after(newElement);
335 succeedingChildren.reverse().forEach(function(child) {
336 newElement.prepend(child);
338 if(suffix.length > 0) {
339 newElement.prepend({text: suffix});
342 return {first: parentElement, second: newElement};
345 divideWithElementNode: function(node, params) {
346 var insertion = this.getNodeInsertion(node),
347 myText = this.getText();
349 if(params.offset === myText.length) {
350 return this.after(node);
352 if(params.offset === 0) {
353 return this.before(node);
356 var lhsText = myText.substr(0, params.offset),
357 rhsText = myText.substr(params.offset),
358 rhsTextNode = this.document.createDocumentNode({text: rhsText});
360 this.setText(lhsText);
361 this.after(insertion.ofNode);
362 insertion.ofNode.after(rhsTextNode);
363 return insertion.ofNode;
367 var documentTransformations = {
368 wrapNodes: function(params) {
369 if(!(params.node1.parent().sameNode(params.node2.parent()))) {
370 throw new Error('Wrapping non-sibling nodes not supported.');
373 var parent = params.node1.parent(),
374 parentContents = parent.contents(),
375 wrapper = this.createDocumentNode({
376 tagName: params._with.tagName,
377 attrs: params._with.attrs}),
378 idx1 = parent.indexOf(params.node1),
379 idx2 = parent.indexOf(params.node2);
387 var insertingMethod, insertingTarget;
389 insertingMethod = 'prepend';
390 insertingTarget = parent;
392 insertingMethod = 'after';
393 insertingTarget = parentContents[idx1-1];
396 for(var i = idx1; i <= idx2; i++) {
397 if(!parentContents[i].getProperty('describesParent')) {
398 wrapper.append(parentContents[i].detach());
402 insertingTarget[insertingMethod](wrapper);
406 _wrapText: function(params) {
407 params = _.extend({textNodeIdx: 0}, params);
408 if(typeof params.textNodeIdx === 'number') {
409 params.textNodeIdx = [params.textNodeIdx];
412 var contentsInside = params.inside.contents(),
413 idx1 = Math.min.apply(Math, params.textNodeIdx),
414 idx2 = Math.max.apply(Math, params.textNodeIdx),
415 textNode1 = contentsInside[idx1],
416 textNode2 = contentsInside[idx2],
417 sameNode = textNode1.sameNode(textNode2),
418 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
419 prefixInside = textNode1.getText().substr(params.offsetStart),
420 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
421 suffixOutside = textNode2.getText().substr(params.offsetEnd)
424 if(!(textNode1.parent().sameNode(textNode2.parent()))) {
425 throw new Error('Wrapping text in non-sibling text nodes not supported.');
428 var wrapperElement = this.createDocumentNode({tagName: params._with.tagName, attrs: params._with.attrs});
429 textNode1.after(wrapperElement);
432 if(prefixOutside.length > 0) {
433 wrapperElement.before({text:prefixOutside});
436 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
437 wrapperElement.append({text: core});
440 if(prefixInside.length > 0) {
441 wrapperElement.append({text: prefixInside});
443 for(var i = idx1 + 1; i < idx2; i++) {
444 if(!contentsInside[i].getProperty('describesParent')) {
445 wrapperElement.append(contentsInside[i]);
448 if(suffixInside.length > 0) {
449 wrapperElement.append({text: suffixInside});
452 if(suffixOutside.length > 0) {
453 wrapperElement.after({text: suffixOutside});
455 return wrapperElement;
457 replaceRoot: function(node) {
458 var insertion = this.getNodeInsertion(node);
460 this._defineDocumentProperties(insertion.ofNode._$);
461 insertion.ofNode.triggerChangeEvent('nodeAdded');
462 return insertion.ofNode;
464 deleteText: function(params) {
465 var ptr, next, toDetach, middle, text;
467 if(params.from.node.sameNode(params.to.node)) {
468 ptr = params.from.node;
469 text = ptr.getText();
470 ptr.setText(text.substr(0, params.from.offset) + text.substr(params.to.offset));
474 // Both edge text nodes need to be edited before anything else happen in case that
475 // they get merged when detaching content between them.
476 params.from.node.setText(params.from.node.getText().substr(0, params.from.offset));
477 params.to.node.setText(params.to.node.getText().substr(params.to.offset));
479 ptr = params.from.node;
482 while(next || ptr.parent()) {
484 if(next.sameNode(params.to.node)) {
487 else if(next.nodeType === Node.ELEMENT_NODE && next.containsNode(params.to.node)) {
501 if(!this.containsNode(params.to.node)) {
502 // The end node was merged during detaching nodes above - there is nothing more left to do.
506 ptr = middle.contents()[0];
507 while(ptr && !ptr.sameNode(params.to.node)) {
508 if(ptr.nodeType === Node.ELEMENT_NODE && ptr.containsNode(params.to.node)) {
509 ptr = ptr.contents()[0];
521 transformations: documentTransformations
524 transformations: documentNodeTransformations
527 transformations: elementNodeTransformations
530 transformations: textNodeTransformations