Merge branch '2.0'
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / js / 3rdParty / codemirror / addon / selection / active-line.js
1 // Because sometimes you need to style the cursor's line.
2 //
3 // Adds an option 'styleActiveLine' which, when enabled, gives the
4 // active line's wrapping <div> the CSS class "CodeMirror-activeline",
5 // and gives its background <div> the class "CodeMirror-activeline-background".
6
7 (function(mod) {
8 if (typeof exports == "object" && typeof module == "object") // CommonJS
9 mod(require("../../lib/codemirror"));
10 else if (typeof define == "function" && define.amd) // AMD
11 define(["../../lib/codemirror"], mod);
12 else // Plain browser env
13 mod(CodeMirror);
14 })(function(CodeMirror) {
15 "use strict";
16 var WRAP_CLASS = "CodeMirror-activeline";
17 var BACK_CLASS = "CodeMirror-activeline-background";
18
19 CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
20 var prev = old && old != CodeMirror.Init;
21 if (val && !prev) {
22 cm.state.activeLines = [];
23 updateActiveLines(cm, cm.listSelections());
24 cm.on("beforeSelectionChange", selectionChange);
25 } else if (!val && prev) {
26 cm.off("beforeSelectionChange", selectionChange);
27 clearActiveLines(cm);
28 delete cm.state.activeLines;
29 }
30 });
31
32 function clearActiveLines(cm) {
33 for (var i = 0; i < cm.state.activeLines.length; i++) {
34 cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
35 cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
36 }
37 }
38
39 function sameArray(a, b) {
40 if (a.length != b.length) return false;
41 for (var i = 0; i < a.length; i++)
42 if (a[i] != b[i]) return false;
43 return true;
44 }
45
46 function updateActiveLines(cm, ranges) {
47 var active = [];
48 for (var i = 0; i < ranges.length; i++) {
49 var line = cm.getLineHandleVisualStart(ranges[i].head.line);
50 if (active[active.length - 1] != line) active.push(line);
51 }
52 if (sameArray(cm.state.activeLines, active)) return;
53 cm.operation(function() {
54 clearActiveLines(cm);
55 for (var i = 0; i < active.length; i++) {
56 cm.addLineClass(active[i], "wrap", WRAP_CLASS);
57 cm.addLineClass(active[i], "background", BACK_CLASS);
58 }
59 cm.state.activeLines = active;
60 });
61 }
62
63 function selectionChange(cm, sel) {
64 updateActiveLines(cm, sel.ranges);
65 }
66 });