theacodes / kicanvas

The KiCAD web viewer
https://kicanvas.org
Other
620 stars 30 forks source link

Issue when constructing `kicanvas-source` with `document.createElement` #74

Open tjhorner opened 8 months ago

tjhorner commented 8 months ago

Describe the bug

When creating a kicanvas-source element programmatically with document.createElement, the browser gets very upset with the following error (or similar):

This behavior can occur when creating kicanvas-sources directly, of course, but it can also occur as a side effect of being in an environment like React, which does the same when building custom elements inside of React components.

To Reproduce

Here is a minimal POC; you can paste it into the JS console of any page with KiCanvas loaded:

const kcSource = document.createElement("kicanvas-source")

It will result in an error in the console.

Expected behavior

The kicanvas-source element should be created dynamically without an error.

Screenshots

image

Environment

Additional context

I believe the issue is being caused around here:

https://github.com/theacodes/kicanvas/blob/5c38d1473362e227defad10dce7f99bca590bbc3/src/kicanvas/elements/kicanvas-embed.ts#L174-L179

...or maybe by this decorator:

https://github.com/theacodes/kicanvas/blob/5c38d1473362e227defad10dce7f99bca590bbc3/src/kicanvas/elements/kicanvas-embed.ts#L181-L182

The browser apparently does not like custom elements manipulating the DOM in their constructor, since it's technically against the spec.

theacodes commented 8 months ago

Looks like we probably just need to move those constructor bits into connectedCallback(). Feel free to send a PR if you'd like, otherwise, I'll get it when I have a chance to sit down with this project again.