Skip to content

DOM-based template conditional/iteration helper alternatives to Solid.js Show/For/etc #43

Open
@trusktr

Description

@trusktr

I'd like to make DOM-based alternatives to some Solid.js components like Show/For/etc. For example:

return html`
<show-when prop:condition=${someBoolean}>
  <template>
    <some-el>foo</some-el>
  </template>
  <template slot="fallback">
    <other-el>bar</other-el>
  </template>
</show-when>

<!-- I'm not sure exactly how this one will work yet, but something like the following with some way to mark how items of an array are referenced and passed to each template instance: -->
<for-each prop:items=${someArray}>
  <template>
    <some-item foo=[[item.foo]] prop:bar=[[item.bar]]></some-item>
  </template>
</for-each>
`

this version will operate on standards:

  • the content of a <template> is inert, so what show-when would do is clone one template or the other into the active DOM based on the condition, only causing custom elements to be instantiated for the cloned content. When someBoolean is true, there will not be an instance of <other-el> because a <template> does not instantiate custom elements in its .content document. The .children of a <template> is empty, the template content is inside of .content and "inert" because it doesn't run any logic (such as custom element constructors and connectedCallbacks). When we do something like someParent.append(template.content.cloneNode(true)), the appended nodes come alive (custom elements constructors and connectedCallbacks run).
  • this means that regardless of the underlying implementation (whether with Solid or not) we can still keep the same outside API surface.
    • This gives us flexibility: with a standards-aligned interface via DOM, it means that this interface will work with anyone who uses it no matter the custom-element framework or non-custom-element framework, and no matter if we change underlying frameworks or implementation details. This makes it easy for us to change our app-level frameworks too, while still keep the template code mostly
      the same (f.e. rather than having to switch from <For> in solid to something else in another framework, we would at worst only need to update the attribute/prop syntax while keep the rest the same)
  • in the (hopefully not too distant) future, we can replace a custom binding syntax ([[]]) with a native binding syntax to get even more standards aligned.

The template.content.cloneNode() stuff is in fact what Solid is using with Show/For and other Solid templates under the hood. It's known to be an optimal method for instantiating DOM.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions