font-load.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import { ViewPlugin } from '@codemirror/view'
  2. import { StateEffect } from '@codemirror/state'
  3. import { updateHasEffect } from '../utils/effects'
  4. const fontLoadEffect = StateEffect.define<readonly FontFace[]>()
  5. export const hasFontLoadedEffect = updateHasEffect(fontLoadEffect)
  6. /**
  7. * A custom extension that listens for an event indicating that fonts have finished loading,
  8. * then dispatches an effect which other extensions can use to recalculate values.
  9. */
  10. export const fontLoad = ViewPlugin.define(view => {
  11. function listener(this: FontFaceSet, event: FontFaceSetLoadEvent) {
  12. view.dispatch({ effects: fontLoadEffect.of(event.fontfaces) })
  13. }
  14. const fontLoadSupport = 'fonts' in document
  15. if (fontLoadSupport) {
  16. // TypeScript doesn't appear to know the correct type for the listener
  17. document.fonts.addEventListener('loadingdone', listener as EventListener)
  18. }
  19. return {
  20. destroy() {
  21. if (fontLoadSupport) {
  22. document.fonts.removeEventListener(
  23. 'loadingdone',
  24. listener as EventListener
  25. )
  26. }
  27. },
  28. }
  29. })