Debian Codegraph @

share/www/js/select.js

raw
1 /* Functionality for finding, storing, and restoring selections
2 *
3 * This does not provide a generic API, just the minimal functionality
4 * required by the CodeMirror system.
5 */
6
7 // Namespace object.
8 var select = {};
9
10 (function() {
11 select.ie_selection = document.selection && document.selection.createRangeCollection;
12
13 // Find the 'top-level' (defined as 'a direct child of the node
14 // passed as the top argument') node that the given node is
15 // contained in. Return null if the given node is not inside the top
16 // node.
17 function topLevelNodeAt(node, top) {
18 while (node && node.parentNode != top)
19 node = node.parentNode;
20 return node;
21 }
22
23 // Find the top-level node that contains the node before this one.
24 function topLevelNodeBefore(node, top) {
25 while (!node.previousSibling && node.parentNode != top)
26 node = node.parentNode;
27 return topLevelNodeAt(node.previousSibling, top);
28 }
29
30 var fourSpaces = "\u00a0\u00a0\u00a0\u00a0";
31
32 select.scrollToNode = function(node, cursor) {
33 if (!node) return;
34 var element = node, body = document.body,
35 html = document.documentElement,
36 atEnd = !element.nextSibling || !element.nextSibling.nextSibling
37 || !element.nextSibling.nextSibling.nextSibling;
38 // In Opera (and recent Webkit versions), BR elements *always*
39 // have a offsetTop property of zero.
40 var compensateHack = 0;
41 while (element && !element.offsetTop) {
42 compensateHack++;
43 element = element.previousSibling;
44 }
45 // atEnd is another kludge for these browsers -- if the cursor is
46 // at the end of the document, and the node doesn't have an
47 // offset, just scroll to the end.
48 if (compensateHack == 0) atEnd = false;
49
50 // WebKit has a bad habit of (sometimes) happily returning bogus
51 // offsets when the document has just been changed. This seems to
52 // always be 5/5, so we don't use those.
53 if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5)
54 return;
55
56 var y = compensateHack * (element ? element.offsetHeight : 0), x = 0,
57 width = (node ? node.offsetWidth : 0), pos = element;
58 while (pos && pos.offsetParent) {
59 y += pos.offsetTop;
60 // Don't count X offset for <br> nodes
61 if (!isBR(pos))
62 x += pos.offsetLeft;
63 pos = pos.offsetParent;
64 }
65
66 var scroll_x = body.scrollLeft || html.scrollLeft || 0,
67 scroll_y = body.scrollTop || html.scrollTop || 0,
68 scroll = false, screen_width = window.innerWidth || html.clientWidth || 0;
69
70 if (cursor || width < screen_width) {
71 if (cursor) {
72 var off = select.offsetInNode(node), size = nodeText(node).length;
73 if (size) x += width * (off / size);
74 }
75 var screen_x = x - scroll_x;
76 if (screen_x < 0 || screen_x > screen_width) {
77 scroll_x = x;
78 scroll = true;
79 }
80 }
81 var screen_y = y - scroll_y;
82 if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) {
83 scroll_y = atEnd ? 1e6 : y;
84 scroll = true;
85 }
86 if (scroll) window.scrollTo(scroll_x, scroll_y);
87 };
88
89 select.scrollToCursor = function(container) {
90 select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true);
91 };
92
93 // Used to prevent restoring a selection when we do not need to.
94 var currentSelection = null;
95
96 select.snapshotChanged = function() {
97 if (currentSelection) currentSelection.changed = true;
98 };
99
100 // Find the 'leaf' node (BR or text) after the given one.
101 function baseNodeAfter(node) {
102 var next = node.nextSibling;
103 if (next) {
104 while (next.firstChild) next = next.firstChild;
105 if (next.nodeType == 3 || isBR(next)) return next;
106 else return baseNodeAfter(next);
107 }
108 else {
109 var parent = node.parentNode;
110 while (parent && !parent.nextSibling) parent = parent.parentNode;
111 return parent && baseNodeAfter(parent);
112 }
113 }
114
115 // This is called by the code in editor.js whenever it is replacing
116 // a text node. The function sees whether the given oldNode is part
117 // of the current selection, and updates this selection if it is.
118 // Because nodes are often only partially replaced, the length of
119 // the part that gets replaced has to be taken into account -- the
120 // selection might stay in the oldNode if the newNode is smaller
121 // than the selection's offset. The offset argument is needed in
122 // case the selection does move to the new object, and the given
123 // length is not the whole length of the new node (part of it might
124 // have been used to replace another node).
125 select.snapshotReplaceNode = function(from, to, length, offset) {
126 if (!currentSelection) return;
127
128 function replace(point) {
129 if (from == point.node) {
130 currentSelection.changed = true;
131 if (length && point.offset > length) {
132 point.offset -= length;
133 }
134 else {
135 point.node = to;
136 point.offset += (offset || 0);
137 }
138 }
139 else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) {
140 currentSelection.changed = true;
141 }
142 }
143 replace(currentSelection.start);
144 replace(currentSelection.end);
145 };
146
147 select.snapshotMove = function(from, to, distance, relative, ifAtStart) {
148 if (!currentSelection) return;
149
150 function move(point) {
151 if (from == point.node && (!ifAtStart || point.offset == 0)) {
152 currentSelection.changed = true;
153 point.node = to;
154 if (relative) point.offset = Math.max(0, point.offset + distance);
155 else point.offset = distance;
156 }
157 }
158 move(currentSelection.start);
159 move(currentSelection.end);
160 };
161
162 // Most functions are defined in two ways, one for the IE selection
163 // model, one for the W3C one.
164 if (select.ie_selection) {
165 function selectionNode(start) {
166 var range = document.selection.createRange();
167 range.collapse(start);
168
169 function nodeAfter(node) {
170 var found = null;
171 while (!found && node) {
172 found = node.nextSibling;
173 node = node.parentNode;
174 }
175 return nodeAtStartOf(found);
176 }
177
178 function nodeAtStartOf(node) {
179 while (node && node.firstChild) node = node.firstChild;
180 return {node: node, offset: 0};
181 }
182
183 var containing = range.parentElement();
184 if (!isAncestor(document.body, containing)) return null;
185 if (!containing.firstChild) return nodeAtStartOf(containing);
186
187 var working = range.duplicate();
188 working.moveToElementText(containing);
189 working.collapse(true);
190 for (var cur = containing.firstChild; cur; cur = cur.nextSibling) {
191 if (cur.nodeType == 3) {
192 var size = cur.nodeValue.length;
193 working.move("character", size);
194 }
195 else {
196 working.moveToElementText(cur);
197 working.collapse(false);
198 }
199
200 var dir = range.compareEndPoints("StartToStart", working);
201 if (dir == 0) return nodeAfter(cur);
202 if (dir == 1) continue;
203 if (cur.nodeType != 3) return nodeAtStartOf(cur);
204
205 working.setEndPoint("StartToEnd", range);
206 return {node: cur, offset: size - working.text.length};
207 }
208 return nodeAfter(containing);
209 }
210
211 select.markSelection = function() {
212 currentSelection = null;
213 var sel = document.selection;
214 if (!sel) return;
215 var start = selectionNode(true),
216 end = selectionNode(false);
217 if (!start || !end) return;
218 currentSelection = {start: start, end: end, changed: false};
219 };
220
221 select.selectMarked = function() {
222 if (!currentSelection || !currentSelection.changed) return;
223
224 function makeRange(point) {
225 var range = document.body.createTextRange(),
226 node = point.node;
227 if (!node) {
228 range.moveToElementText(document.body);
229 range.collapse(false);
230 }
231 else if (node.nodeType == 3) {
232 range.moveToElementText(node.parentNode);
233 var offset = point.offset;
234 while (node.previousSibling) {
235 node = node.previousSibling;
236 offset += (node.innerText || "").length;
237 }
238 range.move("character", offset);
239 }
240 else {
241 range.moveToElementText(node);
242 range.collapse(true);
243 }
244 return range;
245 }
246
247 var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end);
248 start.setEndPoint("StartToEnd", end);
249 start.select();
250 };
251
252 select.offsetInNode = function(node) {
253 var sel = document.selection;
254 if (!sel) return 0;
255 var range = sel.createRange(), range2 = range.duplicate();
256 try {range2.moveToElementText(node);} catch(e){return 0;}
257 range.setEndPoint("StartToStart", range2);
258 return range.text.length;
259 };
260
261 // Get the top-level node that one end of the cursor is inside or
262 // after. Note that this returns false for 'no cursor', and null
263 // for 'start of document'.
264 select.selectionTopNode = function(container, start) {
265 var selection = document.selection;
266 if (!selection) return false;
267
268 var range = selection.createRange(), range2 = range.duplicate();
269 range.collapse(start);
270 var around = range.parentElement();
271 if (around && isAncestor(container, around)) {
272 // Only use this node if the selection is not at its start.
273 range2.moveToElementText(around);
274 if (range.compareEndPoints("StartToStart", range2) == 1)
275 return topLevelNodeAt(around, container);
276 }
277
278 // Move the start of a range to the start of a node,
279 // compensating for the fact that you can't call
280 // moveToElementText with text nodes.
281 function moveToNodeStart(range, node) {
282 if (node.nodeType == 3) {
283 var count = 0, cur = node.previousSibling;
284 while (cur && cur.nodeType == 3) {
285 count += cur.nodeValue.length;
286 cur = cur.previousSibling;
287 }
288 if (cur) {
289 try{range.moveToElementText(cur);}
290 catch(e){return false;}
291 range.collapse(false);
292 }
293 else range.moveToElementText(node.parentNode);
294 if (count) range.move("character", count);
295 }
296 else {
297 try{range.moveToElementText(node);}
298 catch(e){return false;}
299 }
300 return true;
301 }
302
303 // Do a binary search through the container object, comparing
304 // the start of each node to the selection
305 var start = 0, end = container.childNodes.length - 1;
306 while (start < end) {
307 var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle];
308 if (!node) return false; // Don't ask. IE6 manages this sometimes.
309 if (!moveToNodeStart(range2, node)) return false;
310 if (range.compareEndPoints("StartToStart", range2) == 1)
311 start = middle;
312 else
313 end = middle - 1;
314 }
315
316 if (start == 0) {
317 var test1 = selection.createRange(), test2 = test1.duplicate();
318 try {
319 test2.moveToElementText(container);
320 } catch(exception) {
321 return null;
322 }
323 if (test1.compareEndPoints("StartToStart", test2) == 0)
324 return null;
325 }
326 return container.childNodes[start] || null;
327 };
328
329 // Place the cursor after this.start. This is only useful when
330 // manually moving the cursor instead of restoring it to its old
331 // position.
332 select.focusAfterNode = function(node, container) {
333 var range = document.body.createTextRange();
334 range.moveToElementText(node || container);
335 range.collapse(!node);
336 range.select();
337 };
338
339 select.somethingSelected = function() {
340 var sel = document.selection;
341 return sel && (sel.createRange().text != "");
342 };
343
344 function insertAtCursor(html) {
345 var selection = document.selection;
346 if (selection) {
347 var range = selection.createRange();
348 range.pasteHTML(html);
349 range.collapse(false);
350 range.select();
351 }
352 }
353
354 // Used to normalize the effect of the enter key, since browsers
355 // do widely different things when pressing enter in designMode.
356 select.insertNewlineAtCursor = function() {
357 insertAtCursor("<br>");
358 };
359
360 select.insertTabAtCursor = function() {
361 insertAtCursor(fourSpaces);
362 };
363
364 // Get the BR node at the start of the line on which the cursor
365 // currently is, and the offset into the line. Returns null as
366 // node if cursor is on first line.
367 select.cursorPos = function(container, start) {
368 var selection = document.selection;
369 if (!selection) return null;
370
371 var topNode = select.selectionTopNode(container, start);
372 while (topNode && !isBR(topNode))
373 topNode = topNode.previousSibling;
374
375 var range = selection.createRange(), range2 = range.duplicate();
376 range.collapse(start);
377 if (topNode) {
378 range2.moveToElementText(topNode);
379 range2.collapse(false);
380 }
381 else {
382 // When nothing is selected, we can get all kinds of funky errors here.
383 try { range2.moveToElementText(container); }
384 catch (e) { return null; }
385 range2.collapse(true);
386 }
387 range.setEndPoint("StartToStart", range2);
388
389 return {node: topNode, offset: range.text.length};
390 };
391
392 select.setCursorPos = function(container, from, to) {
393 function rangeAt(pos) {
394 var range = document.body.createTextRange();
395 if (!pos.node) {
396 range.moveToElementText(container);
397 range.collapse(true);
398 }
399 else {
400 range.moveToElementText(pos.node);
401 range.collapse(false);
402 }
403 range.move("character", pos.offset);
404 return range;
405 }
406
407 var range = rangeAt(from);
408 if (to && to != from)
409 range.setEndPoint("EndToEnd", rangeAt(to));
410 range.select();
411 }
412
413 // Some hacks for storing and re-storing the selection when the editor loses and regains focus.
414 select.getBookmark = function (container) {
415 var from = select.cursorPos(container, true), to = select.cursorPos(container, false);
416 if (from && to) return {from: from, to: to};
417 };
418
419 // Restore a stored selection.
420 select.setBookmark = function(container, mark) {
421 if (!mark) return;
422 select.setCursorPos(container, mark.from, mark.to);
423 };
424 }
425 // W3C model
426 else {
427 // Find the node right at the cursor, not one of its
428 // ancestors with a suitable offset. This goes down the DOM tree
429 // until a 'leaf' is reached (or is it *up* the DOM tree?).
430 function innerNode(node, offset) {
431 while (node.nodeType != 3 && !isBR(node)) {
432 var newNode = node.childNodes[offset] || node.nextSibling;
433 offset = 0;
434 while (!newNode && node.parentNode) {
435 node = node.parentNode;
436 newNode = node.nextSibling;
437 }
438 node = newNode;
439 if (!newNode) break;
440 }
441 return {node: node, offset: offset};
442 }
443
444 // Store start and end nodes, and offsets within these, and refer
445 // back to the selection object from those nodes, so that this
446 // object can be updated when the nodes are replaced before the
447 // selection is restored.
448 select.markSelection = function () {
449 var selection = window.getSelection();
450 if (!selection || selection.rangeCount == 0)
451 return (currentSelection = null);
452 var range = selection.getRangeAt(0);
453
454 currentSelection = {
455 start: innerNode(range.startContainer, range.startOffset),
456 end: innerNode(range.endContainer, range.endOffset),
457 changed: false
458 };
459 };
460
461 select.selectMarked = function () {
462 var cs = currentSelection;
463 // on webkit-based browsers, it is apparently possible that the
464 // selection gets reset even when a node that is not one of the
465 // endpoints get messed with. the most common situation where
466 // this occurs is when a selection is deleted or overwitten. we
467 // check for that here.
468 function focusIssue() {
469 if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) {
470 var selection = window.getSelection();
471 if (!selection || selection.rangeCount == 0) return true;
472 var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset);
473 return cs.start.node != point.node || cs.start.offset != point.offset;
474 }
475 }
476 if (!cs || !(cs.changed || (webkit && focusIssue()))) return;
477 var range = document.createRange();
478
479 function setPoint(point, which) {
480 if (point.node) {
481 // Some magic to generalize the setting of the start and end
482 // of a range.
483 if (point.offset == 0)
484 range["set" + which + "Before"](point.node);
485 else
486 range["set" + which](point.node, point.offset);
487 }
488 else {
489 range.setStartAfter(document.body.lastChild || document.body);
490 }
491 }
492
493 setPoint(cs.end, "End");
494 setPoint(cs.start, "Start");
495 selectRange(range);
496 };
497
498 // Helper for selecting a range object.
499 function selectRange(range) {
500 var selection = window.getSelection();
501 if (!selection) return;
502 selection.removeAllRanges();
503 selection.addRange(range);
504 }
505 function selectionRange() {
506 var selection = window.getSelection();
507 if (!selection || selection.rangeCount == 0)
508 return false;
509 else
510 return selection.getRangeAt(0);
511 }
512
513 // Finding the top-level node at the cursor in the W3C is, as you
514 // can see, quite an involved process.
515 select.selectionTopNode = function(container, start) {
516 var range = selectionRange();
517 if (!range) return false;
518
519 var node = start ? range.startContainer : range.endContainer;
520 var offset = start ? range.startOffset : range.endOffset;
521 // Work around (yet another) bug in Opera's selection model.
522 if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 &&
523 container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset]))
524 offset--;
525
526 // For text nodes, we look at the node itself if the cursor is
527 // inside, or at the node before it if the cursor is at the
528 // start.
529 if (node.nodeType == 3){
530 if (offset > 0)
531 return topLevelNodeAt(node, container);
532 else
533 return topLevelNodeBefore(node, container);
534 }
535 // Occasionally, browsers will return the HTML node as
536 // selection. If the offset is 0, we take the start of the frame
537 // ('after null'), otherwise, we take the last node.
538 else if (node.nodeName.toUpperCase() == "HTML") {
539 return (offset == 1 ? null : container.lastChild);
540 }
541 // If the given node is our 'container', we just look up the
542 // correct node by using the offset.
543 else if (node == container) {
544 return (offset == 0) ? null : node.childNodes[offset - 1];
545 }
546 // In any other case, we have a regular node. If the cursor is
547 // at the end of the node, we use the node itself, if it is at
548 // the start, we use the node before it, and in any other
549 // case, we look up the child before the cursor and use that.
550 else {
551 if (offset == node.childNodes.length)
552 return topLevelNodeAt(node, container);
553 else if (offset == 0)
554 return topLevelNodeBefore(node, container);
555 else
556 return topLevelNodeAt(node.childNodes[offset - 1], container);
557 }
558 };
559
560 select.focusAfterNode = function(node, container) {
561 var range = document.createRange();
562 range.setStartBefore(container.firstChild || container);
563 // In Opera, setting the end of a range at the end of a line
564 // (before a BR) will cause the cursor to appear on the next
565 // line, so we set the end inside of the start node when
566 // possible.
567 if (node && !node.firstChild)
568 range.setEndAfter(node);
569 else if (node)
570 range.setEnd(node, node.childNodes.length);
571 else
572 range.setEndBefore(container.firstChild || container);
573 range.collapse(false);
574 selectRange(range);
575 };
576
577 select.somethingSelected = function() {
578 var range = selectionRange();
579 return range && !range.collapsed;
580 };
581
582 select.offsetInNode = function(node) {
583 var range = selectionRange();
584 if (!range) return 0;
585 range = range.cloneRange();
586 range.setStartBefore(node);
587 return range.toString().length;
588 };
589
590 select.insertNodeAtCursor = function(node) {
591 var range = selectionRange();
592 if (!range) return;
593
594 range.deleteContents();
595 range.insertNode(node);
596 webkitLastLineHack(document.body);
597
598 // work around weirdness where Opera will magically insert a new
599 // BR node when a BR node inside a span is moved around. makes
600 // sure the BR ends up outside of spans.
601 if (window.opera && isBR(node) && isSpan(node.parentNode)) {
602 var next = node.nextSibling, p = node.parentNode, outer = p.parentNode;
603 outer.insertBefore(node, p.nextSibling);
604 var textAfter = "";
605 for (; next && next.nodeType == 3; next = next.nextSibling) {
606 textAfter += next.nodeValue;
607 removeElement(next);
608 }
609 outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling);
610 }
611 range = document.createRange();
612 range.selectNode(node);
613 range.collapse(false);
614 selectRange(range);
615 }
616
617 select.insertNewlineAtCursor = function() {
618 select.insertNodeAtCursor(document.createElement("BR"));
619 };
620
621 select.insertTabAtCursor = function() {
622 select.insertNodeAtCursor(document.createTextNode(fourSpaces));
623 };
624
625 select.cursorPos = function(container, start) {
626 var range = selectionRange();
627 if (!range) return;
628
629 var topNode = select.selectionTopNode(container, start);
630 while (topNode && !isBR(topNode))
631 topNode = topNode.previousSibling;
632
633 range = range.cloneRange();
634 range.collapse(start);
635 if (topNode)
636 range.setStartAfter(topNode);
637 else
638 range.setStartBefore(container);
639
640 var text = range.toString();
641 return {node: topNode, offset: text.length};
642 };
643
644 select.setCursorPos = function(container, from, to) {
645 var range = document.createRange();
646
647 function setPoint(node, offset, side) {
648 if (offset == 0 && node && !node.nextSibling) {
649 range["set" + side + "After"](node);
650 return true;
651 }
652
653 if (!node)
654 node = container.firstChild;
655 else
656 node = node.nextSibling;
657
658 if (!node) return;
659
660 if (offset == 0) {
661 range["set" + side + "Before"](node);
662 return true;
663 }
664
665 var backlog = []
666 function decompose(node) {
667 if (node.nodeType == 3)
668 backlog.push(node);
669 else
670 forEach(node.childNodes, decompose);
671 }
672 while (true) {
673 while (node && !backlog.length) {
674 decompose(node);
675 node = node.nextSibling;
676 }
677 var cur = backlog.shift();
678 if (!cur) return false;
679
680 var length = cur.nodeValue.length;
681 if (length >= offset) {
682 range["set" + side](cur, offset);
683 return true;
684 }
685 offset -= length;
686 }
687 }
688
689 to = to || from;
690 if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start"))
691 selectRange(range);
692 };
693 }
694 })();