Apply decorations directly through an editor method?

Thanks, now I’m starting to get it!

I managed to get it to work, code is below.

Helper Function:

function applyDecoration (state, view, fromPos, toPos) {
  let transaction = state.tr.setMeta("directDecoration", {fromPos: fromPos, toPos: toPos})
  view.dispatch(transaction)
}

Plugin:

let directDecoration= new Plugin({
  state: {
    init() {
      // No decorations set by default
    },
    apply(tr, value) {
      if (tr.getMeta("directDecoration")) {
        const {fromPos, toPos} = tr.getMeta("directDecoration")
        return DecorationSet.create(tr.doc, [
          Decoration.inline(fromPos, toPos, {style: "color: purple"})
        ])
      } else {
         // map "other" changes so our decoration "stays put" 
         // (e.g. user is typing so decoration's pos must change)
        return value.map(tr.mapping, tr.doc)
      }
    }
  },
  props: {
    decorations(state) {
      return directDecoration.getState(state)
    }
  }
})
2 Likes