Skip to content

Commit

Permalink
src: Change the way we handle static stylesheet
Browse files Browse the repository at this point in the history
Previously we deduped duplicate styles from being added to the
document.head by only adding the own method of a component.

This time we keep a reference to the static function in a
seen array and only call it once.

We expose a new static method called `registerStyles()` which
can be called by any child class that wants to inherit and
overwrite styles

For example

```js
class MyDialog extends Dialog {
  static stylesheet () {
    Tonic.registerStyles(super.stylesheet)
    return 'CSS'
  }
}
```
  • Loading branch information
Raynos committed Mar 6, 2020
1 parent f9fdff0 commit 0e652cf
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,18 @@ class Tonic extends window.HTMLElement {
Tonic._tags = Object.keys(Tonic._reg).join()
window.customElements.define(htmlName, c)

Tonic.addStyles(c)
if (c.stylesheet) {
Tonic.registerStyles(c.stylesheet)
}
}

static addStyles (c) {
if (Object.prototype.hasOwnProperty.call(c, 'stylesheet')) {
const styleNode = document.createElement('style')
styleNode.appendChild(document.createTextNode(c.stylesheet()))
if (document.head) document.head.appendChild(styleNode)
}
static registerStyles (stylesheetFn) {
if (Tonic._seenStylesheets.includes(stylesheetFn)) return
Tonic._seenStylesheets.push(stylesheetFn)

const styleNode = document.createElement('style')
styleNode.appendChild(document.createTextNode(stylesheetFn()))
if (document.head) document.head.appendChild(styleNode)
}

static escape (s) {
Expand Down Expand Up @@ -351,6 +354,7 @@ Object.assign(Tonic, {
_states: {},
_children: {},
_reg: {},
_seenStylesheets: [],
_index: 0,
version: typeof require !== 'undefined' ? require('./package').version : null,
SPREAD: /\.\.\.\s?(__\w+__\w+__)/g,
Expand Down

0 comments on commit 0e652cf

Please sign in to comment.