autorefresh.js 1.7 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')
  5. // CommonJS
  6. mod(require('../../lib/codemirror'))
  7. else if (typeof define == 'function' && define.amd)
  8. // AMD
  9. define(['../../lib/codemirror'], mod)
  10. // Plain browser env
  11. else mod(CodeMirror)
  12. })(function (CodeMirror) {
  13. 'use strict'
  14. CodeMirror.defineOption('autoRefresh', false, function (cm, val) {
  15. if (cm.state.autoRefresh) {
  16. stopListening(cm, cm.state.autoRefresh)
  17. cm.state.autoRefresh = null
  18. }
  19. if (val && cm.display.wrapper.offsetHeight == 0) startListening(cm, (cm.state.autoRefresh = { delay: val.delay || 250 }))
  20. })
  21. function startListening(cm, state) {
  22. function check() {
  23. if (cm.display.wrapper.offsetHeight) {
  24. stopListening(cm, state)
  25. if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight) 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. })