annotatescrollbar.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. CodeMirror.defineExtension("annotateScrollbar", function(className) {
  13. return new Annotation(this, className);
  14. });
  15. function Annotation(cm, className) {
  16. this.cm = cm;
  17. this.className = className;
  18. this.annotations = [];
  19. this.div = cm.getWrapperElement().appendChild(document.createElement("div"));
  20. this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none";
  21. this.computeScale();
  22. var self = this;
  23. cm.on("refresh", this.resizeHandler = function(){
  24. if (self.computeScale()) self.redraw();
  25. });
  26. }
  27. Annotation.prototype.computeScale = function() {
  28. var cm = this.cm;
  29. var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight) /
  30. cm.heightAtLine(cm.lastLine() + 1, "local");
  31. if (hScale != this.hScale) {
  32. this.hScale = hScale;
  33. return true;
  34. }
  35. };
  36. Annotation.prototype.update = function(annotations) {
  37. this.annotations = annotations;
  38. this.redraw();
  39. };
  40. Annotation.prototype.redraw = function() {
  41. var cm = this.cm, hScale = this.hScale;
  42. if (!cm.display.barWidth) return;
  43. var frag = document.createDocumentFragment(), anns = this.annotations;
  44. for (var i = 0, nextTop; i < anns.length; i++) {
  45. var ann = anns[i];
  46. var top = nextTop || cm.charCoords(ann.from, "local").top * hScale;
  47. var bottom = cm.charCoords(ann.to, "local").bottom * hScale;
  48. while (i < anns.length - 1) {
  49. nextTop = cm.charCoords(anns[i + 1].from, "local").top * hScale;
  50. if (nextTop > bottom + .9) break;
  51. ann = anns[++i];
  52. bottom = cm.charCoords(ann.to, "local").bottom * hScale;
  53. }
  54. var height = Math.max(bottom - top, 3);
  55. var elt = frag.appendChild(document.createElement("div"));
  56. elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: " + top + "px; height: " + height + "px";
  57. elt.className = this.className;
  58. }
  59. this.div.textContent = "";
  60. this.div.appendChild(frag);
  61. };
  62. Annotation.prototype.clear = function() {
  63. this.cm.off("refresh", this.resizeHandler);
  64. this.div.parentNode.removeChild(this.div);
  65. };
  66. });