koaning / justcharts

Just charts. Really.
https://calmcode.io/labs/justcharts.html
21 stars 2 forks source link

Suggestion: use custom elements #3

Open chmp opened 11 months ago

chmp commented 11 months ago

Hi @koaning,

Really cool idea. That reminds of a similar setup I use. In principle the functionality is the same, but I use custom elements. I beleive they have a couple of advantages over the "onload" event:

That's the snippet I'm using:

customElements.define(
    "vegalite-plot",
    class extends HTMLElement {
        connectedCallback() {
            if(!this.isConnected) return;
            if(this.innerHTML.trim() == "") return;

            const spec = JSON.parse(this.innerHTML);
            const shadow = this.attachShadow({mode: 'open'});
            const el = shadow.appendChild(document.createElement("div"));

            vegaEmbed(el, spec, {actions: false});
        }
    }
);

To react to changes to the element after it has been aded to the DOM, you probably would need to use a MutationObserver. Something along the lines of this:

/* ... */
    new MutationObserver(() => this.render()).observe(
        this,  {
            subtree: true,
            childList: true, 
            attributes: true, 
            attributeFilter: ["schema-url"],
        });
/* ... */

Feel free to ignore my suggestion. Happy to whip up a PR, if you're intested (although the first code snippet should be mostly it :D).

koaning commented 11 months ago

The fact that it works nicely with htmx certainly is a plus.

I don't have that much time anymore (I have a 1 year old now) but I'd love to revisit this on the medium term. If you have an idea for a PR I'm all ears ... but a few concerns:

  1. Can we do this in such a way that we don't break the API?
  2. Might it be possible to add unit tests? I guess we might introduce playwright for this.
chmp commented 10 months ago

Okay, I realized I'm also bit swamped at the moment - hence the delay :)

I hacked together an implementation in #4 and hosted a demo here - as always with htmx you can see the details with "show source".

To your points:

  1. I would suggest to break the API, in so far, as to rename the element to "vegalite-plot" or "vega-chart". The element must contain a hyphen to be standard compliant.
  2. TBH, as I have no experience with playwright, I fear this might mean a bit more effort than I am willing to put into this topic
chmp commented 10 months ago

I closed the PR, as I think it did have a couple of issues. I implemented a better version this idea for myself and wrote a bit about the underlying design here. Feel free to copy the implementation / tests.