Best way to update widgets live while typing?

I’m trying to insert widgets on lines that contain a particular keyword \newpage, and the widget is simply a marker that displays whatever the current page count tally is up to that point in the document.

What’s the best way to update those widgets as the user is typing in the document, potentially moving/creating/deleting new instances of the \newpage keyword? Right now I’m running CodeMirror with React, and every time the Codemirror content updates, I trigger a function to gather all of my widgets using document.getElementsByClassName and then remove them all, then immediately scan each line again looking for the \newpage keyword to re-generate new widgets in the appropriate places. This is a lot of clearing and creating of widgets with every user keystroke and seems inefficient (especially as the document size increases), but I’m struggling to figure out a cleaner way to ensure all the widgets are updated live as the user types. Is there a better approach to this?

You could use transaction.changes to determine which range is changed, and only re-scan lines around that, using RangeSet.update to update the set of widget decorations.

Looks like that requires V6? We haven’t updated yet because it’s still in beta phase.

Is there a v5 solution to this or would you recommend we update?

Ah, on 5 you’ll have to track your own set of marks, and figuring out the changed range is more annoying (change events + CodeMirror.changeEnd) can help, but the general principle is the same.