CM6 WidgetType toDOM/updateDOM context

Right now it doesn’t seems like WidgetType.toDOM/WidgetType.updateDOM can get any information about where in the document it’s located at, so an instance of a Widget must include any contextual information (passed in via the constructor).

The closest example I found is this fold widget code, which conveniently works around the problem by using the dom click event to find out which line has been clicked.

Here’s my use case: I’m attempting to use a Decoration.widget() to insert an image right after a URL corresponding to an image.

Currently, I’m constantly re-creating the widget with Decoration.widget({widget: new ImageWidget(imageUrl)}). Is there a better way to do this?

The idea is to give widgets as little dependencies as possible, so that they don’t have to be re-rendered every time something changes elsewhere in the document. Is there anything, beyond the image’s URL, that your widget depends on? If not, then putting the URL in the widget instance works, doesn’t it? Recreating the widget instance, as long as they have a proper eq method, shouldn’t be very expensive, since the widget DOM won’t be re-rendered (this is why the indirection through WidgetType exists).

Ok that sounds like what I’m doing is exactly the recommended way :+1: for now.

I was hoping to add a click handler that would select the URL text from the document. I don’t suppose that would fit this model very well though?

You could find the widget’s position through posAtDOM and then subtract the length of the link (or match against that part of the document) to create the selection range.

Ok that could work, might be just a tad bit hairy since the image isn’t rendered exactly at the url’s position.

The two formats we use:




where is the image.

I’m tempted to use a WeakMap<HTMLImageElement, ContextInformation> and store up-to-date info on toDOM/updateDOM (or just use data- attributes). This is because we have the most information (parse tree, etc) when the widget is generated, but going backwards from a click event to re-understand the document’s parse tree is just tedious work that could be error prone since it may not interpret the document identically.

EDIT: I’m anticipating more use of this pattern for more advanced use cases, for example:

<code to some mermaid diagram>
□ <-- the widget that would select the source code above when clicked