Decorator iteration on click event

Hey there!
I wonder if there is a possibility to iterate through all decorations on click event.
Please take a look at the example below and the comments in the code

const DecoPlugin = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet;

    constructor(view: EditorView) {
      this.decorations = deco(view);
    }

    update(update: ViewUpdate) {
      if (update.docChanged || update.viewportChanged) {
        this.decorations = deco(update.view);
      }
    }
  },
  {
    decorations: (v) => v.decorations,
    eventHandlers: {
      click: (e, view) => {
        const target = e.target as HTMLElement;

        // here I would like to check if the clicked element is a decorator
        // if YES, I want to take its coords (from, to)
      }
    }
  }
);

const deco = (view: EditorView) => {
  const widgets: Range<Decoration>[] = [];
  
  // here I add lots of decorators
  // widget.push(Decoration.replace(...)

  return Decoration.set(widgets, true);
};

Your event handler can access this.decorations, and you can use posAtCoords to get a position from a mouse event.

1 Like

thanks a lot!

i have the same situation but this inside handler is undefined. Any help please :slight_smile:
I’m quite confused

const locatorsView = ViewPlugin.fromClass(class {
    decorations; 

    constructor(view) {
        this.decorations = locatorBoxes(view)
    }

    update(update) {
        if (update.docChanged || update.viewportChanged)
            this.decorations = locatorBoxes(update.view)
    }
}, {
    decorations: v => v.decorations,

    eventHandlers: {
        mousedown: (e, view) => {
            let pos = view.posAtDOM(e.target);
            let deco;
            console.log(e)
            console.log(view)
            console.log(this);
        }
    }
})

Weird. When I do that this holds the plugin instance. What version of @codemirror/view are you using?

I also thought that it is the problem so I reinstalled all packages, but still got the error
image

Though in package-lock.json I have these dependencies from basic-setup… But I dont use it, basic-setup is an option in uiw/react-codemirror component, which I disabled

Oh, right, you’re using an arrow function for the event handler. Those can’t be bound. Use a function expression or shorthand method syntax.

1 Like

Thanks thanks thanks a lot! It helped :yum: