font-load.ts 934 B

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. const plugin = ViewPlugin.define(view => {
  7. function listener(this: FontFaceSet, event: FontFaceSetLoadEvent) {
  8. view.dispatch({ effects: fontLoadEffect.of(event.fontfaces) })
  9. }
  10. const fontLoadSupport = 'fonts' in document
  11. if (fontLoadSupport) {
  12. // TypeScript doesn't appear to know the correct type for the listener
  13. document.fonts.addEventListener('loadingdone', listener as EventListener)
  14. }
  15. return {
  16. destroy() {
  17. if (fontLoadSupport) {
  18. document.fonts.removeEventListener(
  19. 'loadingdone',
  20. listener as EventListener
  21. )
  22. }
  23. },
  24. }
  25. })
  26. export function fontLoad() {
  27. return plugin
  28. }