autorefresh.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://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.defineOption("autoRefresh", false, function(cm, val) {
  13. if (cm.state.autoRefresh) {
  14. stopListening(cm, cm.state.autoRefresh)
  15. cm.state.autoRefresh = null
  16. }
  17. if (val && cm.display.wrapper.offsetHeight == 0)
  18. startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250})
  19. })
  20. function startListening(cm, state) {
  21. function check() {
  22. if (cm.display.wrapper.offsetHeight) {
  23. stopListening(cm, state)
  24. if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight)
  25. cm.refresh()
  26. } else {
  27. state.timeout = setTimeout(check, state.delay)
  28. }
  29. }
  30. state.timeout = setTimeout(check, state.delay)
  31. state.hurry = function() {
  32. clearTimeout(state.timeout)
  33. state.timeout = setTimeout(check, 50)
  34. }
  35. CodeMirror.on(window, "mouseup", state.hurry)
  36. CodeMirror.on(window, "keyup", state.hurry)
  37. }
  38. function stopListening(_cm, state) {
  39. clearTimeout(state.timeout)
  40. CodeMirror.off(window, "mouseup", state.hurry)
  41. CodeMirror.off(window, "keyup", state.hurry)
  42. }
  43. });