Skip to content

Does this code go against how lit-element should be used? #845

Closed
@mercmobily

Description

@mercmobily

Hi,

I am creating an issue because I feel that if this is a good idea, it should catch the maintainers' attention; and if it's a bad idea, it should be "officially bad".

I want to create some elements (who doesn't?) but at the same time I want to give designers a chance to really theme them (again, who doesn't?). I realise there are custom properties etc., but I don't think they go quite far enough.

This is what I want the end result to be:

        <fancy-input-text label="The label">
          <style slot="style">
            #label {
              color: blue
            }
          </style>
        </fancy-input-text>

I achieved this by writing StyleableMixin.js:

import { html } from 'lit-element'

export const StyleableMixin = (base) => {
  return class Base extends base {
    firstUpdated () {
      super.firstUpdated()

      const styleSlot = this.shadowRoot.querySelector('#style-slot')
      if (styleSlot) {
        for (const styleElement of styleSlot.assignedElements()) {
          if (styleElement.tagName === 'STYLE') {
            this.shadowRoot.appendChild(styleElement)
          }
        }
      }
    }

    get customStyleSlot () {
      return html`
          <slot name="style" id="style-slot"></slot>
        `
    }
  }
}

So, FancyInputText.js that uses the mixin is simply:

import { LitElement, html } from 'lit-element'
import { StyleableMixin } from './mixins/StyleableMixin.js'

export class FancyInputText extends StyleableMixin(LitElement) {
  static get properties () {
    return {
      label: { type: String }
    }
  }

  render () {
    return html`
      ${this.customStyleSlot}
      <label id="label" for="native">
        <div id="label-text">${this.label}</div>
      </label>
      <input type="text" id="native">
    `
  }
}
customElements.define('fancy-input-text', FancyInputText)

Basically, StyleableMixin will copy over to the shadow DOM any style tags defined in in the slots named style. Designers have a way to really change whatever they like about an element, without getting FOUC.

Is this an anti-pattern? Am I doing something absolutely terrible? Or is this what it looks like it is: the holy grain of allowing designers to really change the CSS when custom properties don't go far enough?

Please feel free to throw tomatoes at me if I deserve it!

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