c35df3bed260a3c0079c8464155a08bf463f3472035c82e587256472dcaaf8405884e8cd1bebfa6153d5a2a4da2451570ab0aeadc4f3ca1a0e4db4f3b374e1 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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"), editors = []
  9. for (let i = 0; i < byClass.length; i++) {
  10. let cm = byClass[i].CodeMirror
  11. if (cm) editors.push(cm)
  12. }
  13. if (editors.length) editors[0].operation(() => {
  14. for (let i = 0; i < editors.length; i++) f(editors[i])
  15. })
  16. }
  17. let globalsRegistered = false
  18. export function ensureGlobalHandlers() {
  19. if (globalsRegistered) return
  20. registerGlobalHandlers()
  21. globalsRegistered = true
  22. }
  23. function registerGlobalHandlers() {
  24. // When the window resizes, we need to refresh active editors.
  25. let resizeTimer
  26. on(window, "resize", () => {
  27. if (resizeTimer == null) resizeTimer = setTimeout(() => {
  28. resizeTimer = null
  29. forEachCodeMirror(onResize)
  30. }, 100)
  31. })
  32. // When the window loses focus, we want to show the editor as blurred
  33. on(window, "blur", () => forEachCodeMirror(onBlur))
  34. }
  35. // Called when the window resizes
  36. function onResize(cm) {
  37. let d = cm.display
  38. // Might be a text scaling operation, clear size caches.
  39. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  40. d.scrollbarsClipped = false
  41. cm.setSize()
  42. }