Suppose I'm making a simple SVG game. I want to make custom elements with shadow roots that consist of SVG primitives (<rect>
, <circle>
, etc). The result would be like this:
<svg>
<redwood-tree position="10 20"></redwood-tree>
<player-tank position="30 50"></player-tank>
<enemy-tank position="50 100"></enemy-tank>
<!-- ... etc ... -->
</svg>
where each one of those elements could be defined as
customElements.define('player-tank', class extends SVGRectElement {
constructor() {
this.root = this.attachShadow({mode:'closed'})
this.root.innerHTML = `<rect width="10" height="10"></rect>`
// ... some more code to map `position` attribute to `x/y` attributes ...
}
})
Demo (nothing happens): https://jsfiddle.net/pem90k9a (but if you try to place the player-tank
element outside of an SVG tree, then it will say Uncaught TypeError: Illegal constructor
anyways since we've extended SVGRectElement
.
Why is SVG not component-friendly?
A solution is to use <div>
s, and each item (player-tank, enemy-tank, etc) can be a separate <svg>
tree, but anyways it would still be intuitive for it to just work (rather than resulting in nothing).
We'd have to modify the parser even more. So we opted not to do that to reduce complexity.
It just needs to look at the composed tree. The rendering should be decoupled from parsing, it would be proper. Idk how complex that is, but it seems worthwhile.
We'd have to modify the parser even more. So we opted not to do that to reduce complexity.
Great design and development ethos! Push the complexity on the developers and end-users!
Most helpful comment
It just needs to look at the composed tree. The rendering should be decoupled from parsing, it would be proper. Idk how complex that is, but it seems worthwhile.