Roo/lib/Selection.js
[roojs1] / Roo / lib / Selection.js
1 /**
2  * @class Roo.lib.Selection
3  * @constructor
4  * This is a toolkit, normally used to copy features into a Dom Selection element
5  * Roo.lib.Selection.wrap(x);
6  *
7  *
8  *
9  */
10 Roo.lib.Selection = function() { };
11
12 /**
13  * Wrap a Dom Range object, to give it new features...
14  * @static
15  * @param {Range} the range to wrap
16  */
17 Roo.lib.Selection.wrap = function(r, doc) {
18     Roo.apply(r, Roo.lib.Selection.prototype);
19     r.ownerDocument = r; // usefull so we dont have to keep referening to it.
20 };
21 /**
22  * find a parent node eg. LI / OL
23  * @param {string|Array} node name or array of nodenames
24  * @return {DomElement|false}
25  */
26 Roo.apply(Roo.lib.Selection.prototype,
27 {
28     /**
29      * the owner document
30      */
31     ownerDocument : false,
32     
33     getRangeAt : function(n)
34     {
35         return Roo.lib.Range.wrap(Selection.prototype.getRangeAt.call(this,n));
36     },
37     
38     /**
39      * insert node at selection 
40      * @param {DomElement|string} node
41      * @param {string} cursor (after|in|none) where to place the cursor after inserting.
42      */
43     insertNode: function(node, cursor)
44     {
45         if (typeof(node) == 'string') {
46             node = this.ownerDocument.createElement(node);
47             if (cursor == 'in') {
48                 node.innerHTML = ' ';
49             }
50         }
51         
52         var range = this.getRangeAt(0);
53         
54         if (this.type != 'Caret') {
55             range.deleteContents();
56         }
57         range.insertNode(node);
58         if (cursor == 'none') {
59             return;
60         }
61         var sn = node.childNodes[0]; // select the contents.
62         if (cursor == 'after') {
63             sn = node.insertAdjacentHTML('afterend', ' ');
64         }
65         this.cursorStart(sn);
66     },
67     cursorStart : function(n)
68     {
69         var range = this.getRangeAt(0);
70         range = range.cloneRange();
71         range.selectNode(sn);
72         
73         range.collapse(false);
74          
75         this.removeAllRanges();
76         this.addRange(range);
77     }
78     
79     
80     
81     
82 });