1 define(function(require) {
5 var $ = require('libs/jquery');
7 var Selection = function(canvas, params) {
9 $.extend(this, params);
12 var CaretSelection = function(canvas, params) {
13 Selection.call(this, canvas, params);
15 CaretSelection.prototype = Object.create(Selection.prototype);
16 $.extend(CaretSelection.prototype, {
17 toDocumentFragment: function() {
18 var doc = this.canvas.wlxmlDocument;
19 return doc.createFragment(doc.CaretFragment, {node: this.element.wlxmlNode, offset: this.offset});
23 var TextSelection = function(canvas, params) {
24 Selection.call(this, canvas, params);
26 TextSelection.prototype = Object.create(Selection.prototype);
27 $.extend(TextSelection.prototype, {
28 toDocumentFragment: function() {
29 var doc = this.canvas.wlxmlDocument,
30 anchorNode = this.anchorElement ? this.anchorElement.wlxmlNode : null,
31 focusNode = this.focusElement ? this.focusElement.wlxmlNode : null;
33 if(!anchorNode || !focusNode) {
37 if(anchorNode.isSiblingOf(focusNode)) {
38 return doc.createFragment(doc.TextRangeFragment, {
40 offset1: this.anchorOffset,
42 offset2: this.focusOffset,
46 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
47 return doc.createFragment(doc.RangeFragment, {
48 node1: siblingParents.node1,
49 node2: siblingParents.node2
55 var NodeSelection = function(canvas, params) {
56 Selection.call(this, canvas, params);
58 NodeSelection.prototype = Object.create(Selection.prototype);
59 $.extend(NodeSelection.prototype, {
60 toDocumentFragment: function() {
61 var doc = this.canvas.wlxmlDocument;
62 doc.createFragment(doc.NodeFragment, {node: this.element.wlxmlNode});
67 var isText = function(node) {
69 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
73 caret: CaretSelection,
74 textSelection: TextSelection,
75 nodeSelection: NodeSelection
79 fromParams: function(canvas, params) {
80 return new types[params.type](canvas, params);
82 fromNativeSelection: function(canvas) {
84 var nativeSelection = window.getSelection(),
87 if(nativeSelection.focusNode) {
88 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
91 element: canvas.getDocumentElement(nativeSelection.focusNode),
92 offset: nativeSelection.focusOffset
94 } else if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
96 type: 'textSelection',
97 anchorElement: canvas.getDocumentElement(nativeSelection.anchorNode),
98 anchorOffset: nativeSelection.anchorOffset,
99 focusElement: canvas.getDocumentElement(nativeSelection.focusNode),
100 focusOffset: nativeSelection.focusOffset
103 } else if((element = canvas.getCurrentNodeElement())) {
105 type: 'nodeSelection',
110 return this.fromParams(canvas, params);