Drag and drop with Web Components/Custom Elements instead of ports?


#1

I’ve heard that it’s possible to utilize WCs, or more specifically, custom elements as an alternative to JS interop via ports. I think I’ve heard folks use this technique with drag and drop, for example.

Can someone explain or provide code snippets on how this would work? I’m aware that one can create an arbitrary DOM node in Elm with Html.node but don’t quite grok the data passing techniques.

Thanks.


#2

Disclaimer: this is based on my limited understanding of custom elements – please correct me if I got something wrong!

A custom element allows you to implement special behaviour for a “custom element”, that is, you choose a name that will be used in HTML and provide some JavaScript to manipulate the element in response to various events.

Think of an <input> element. It does a lot more than a <div> or <span>, but it’s still a single element. The implementation logic is hidden away, so all you need to do is set some attributes and/or properties and you’ve got a nice text input.

You can do the same thing with a Web Components’ “custom element”. You register the name, and provide an implementation. The browser will call relevant functions in your implementation when something happens, like when some external code changes a property of the custom element. Custom elements have their own “shadow dom”, where they can render any number of children to implement their behavior. This “shadow dom” is hidden from JavaScript. (You can inspect the shadow dom by enabling it in the devtools’ options – many native elements like <input>s use the shadow dom!).

As far as how to create a custom element, I’d refer you to that MDN page you linked. Is there anything in particular that was confusing on that page?


#3

something like the following in the view?

....
Html.node "my-element"
    [ Html.Attributes.property "xCoord" myX
    , Html.Attributes.property "yCoord" myY
    ]
    [ ... ]

#4

@luke did a presentation on custom elements, at the Oregon Meetup. Here is a link to his presentation notes, with links to examples. Not drag and drop, but maybe useful.


#5

@pruett Have you seen how this is done? https://github.com/huytd/kanelm/blob/master/src/EventHelpers.elm


#6

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.