global_events.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { onBlur } from "../display/focus.js"
  2. import { on } from "../util/event.js"
  3. // These must be handled carefully, because naively registering a
  4. // handler for each editor will cause the editors to never be
  5. // garbage collected.
  6. function forEachCodeMirror(f) {
  7. if (!document.getElementsByClassName) return
  8. let byClass = document.getElementsByClassName("CodeMirror")
  9. for (let i = 0; i < byClass.length; i++) {
  10. let cm = byClass[i].CodeMirror
  11. if (cm) f(cm)
  12. }
  13. }
  14. let globalsRegistered = false
  15. export function ensureGlobalHandlers() {
  16. if (globalsRegistered) return
  17. registerGlobalHandlers()
  18. globalsRegistered = true
  19. }
  20. function registerGlobalHandlers() {
  21. // When the window resizes, we need to refresh active editors.
  22. let resizeTimer
  23. on(window, "resize", () => {
  24. if (resizeTimer == null) resizeTimer = setTimeout(() => {
  25. resizeTimer = null
  26. forEachCodeMirror(onResize)
  27. }, 100)
  28. })
  29. // When the window loses focus, we want to show the editor as blurred
  30. on(window, "blur", () => forEachCodeMirror(onBlur))
  31. }
  32. // Called when the window resizes
  33. function onResize(cm) {
  34. let d = cm.display
  35. // Might be a text scaling operation, clear size caches.
  36. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  37. d.scrollbarsClipped = false
  38. cm.setSize()
  39. }