Cursor issue in drawSelection after font reflow when using a custom font

I’m using a custom font (Open Sans) in CodeMirror 6.

When the font finishes loading, the page layout is reflowed. After this reflow, the cursor rendered by drawSelection becomes incorrect (misaligned / visually abnormal).

This seems to be caused by the font metrics changing after the initial render, while drawSelection does not get properly updated to reflect the new layout.

You can download `Codemirror.html` to quickly reproduce the issue.

Codemirror.html (1.3 KB)

Simply refreshing the selection area after the font finishes loading will resolve this issue.

if (document.fonts) {
    document.fonts.addEventListener('loadingdone', () => {
        view.dispatch({selection: {anchor: view.state.selection.main.from}})
    })
}

I believe this issue should be fixed in draw-selection.ts

The library was already listening to fonts.ready, but assuming nothing changed if content or line height stayed precisely the same. Attached patch improves this and, for me, fixes the issue in your reproduction HTML.

Thanks for your hard work!

Fonts may be `lazy-loaded`, especially when using `unicode-range`, in which case `document.fonts.ready` may no longer be executed.

I believe this is a potential issue.

I know. The browser platform makes some things really hard. If you know of a non-terrible (i.e. no polling) way to reliably be notified of font changes, I’d love to hear about it.

In Chromium, I use document.fonts.addEventListener(‘loadingdone’, () => {}).

document.fonts.addEventListener doesn’t seem to work in Safari, so in Safari I use document.fonts.onloadingdone = () => {}.

One thing is certain: in Chromium, document.fonts.addEventListener(‘loadingdone’, () => {}) works 100% reliably.