Async decorations

Hello,

I was wondering if it’s possible to apply decorations asynchronously? For example, if I hit a service for spell checking and would then like to underline any misspellings. I followed along with the lint example, but I wasn’t sure how to return the Decoration Set as a property if the set gets created through an async function?

1 Like

What you do is write a plugin that reads some kind of transaction meta property to add the decoration, and have your async code fire such a transaction when it receives a response.

Great thank you!! Do you have any suggestions on how to trigger the spell check (besides normal state changes) in a way that’s not firing the check constantly? Is there a way to somehow throttle the event handler with the state changes. I realize that’s probably sounds odd, but thought I would check anyway … :slight_smile:

You’ll probably want to only do a check when a transaction that changes the document happens. And then possibly debounce it.

1 Like

Got it. With you so far. Is state.apply enough to trigger the decorations props to re-run (so to speak). I do a check in the plugin state’s apply

if (transaction.docChanged) {
          check(newState)
}

In check, I do a state.apply:

    state.apply(
          state.tr.setMeta(key, {
            decorations: DecorationSet.create(state.doc, decos)
          })
  )

This does run the apply of the plugin, but the decoration props is not updating. I am wondering if this is because I am doing state.apply and not a dispatch, but I am not sure how to access dispatch from this area of the code since I can’t (or don’t know how to) access the editorView from here.

Yes, it should be, but it’d be cleaner to do this in the update method of a plugin view, since state updates are about the immutable data flow, and not really the place for imperative event handling.

Doing state.apply will just create a new state, but not do anything with it. You probably want view.dispatch.

For debouncing you may wish to investigate lodash’s implementation, it’s awesome

I got all this hooked up and working! Thanks so much!!

When there’s a misspelling, the word gets a class decoration to underline it. When the user types the underlines flash (like it’s toggling on and off). I assume that is because the UI is re-drawing. Is there a way around that?