gem-mine / webpack-css-themes-plugin

7 stars 2 forks source link

Switch between compiled themes #3

Closed itayganor closed 4 years ago

itayganor commented 4 years ago

After a successful build, there are multiple css files generated.

How can I switch between them when I run the app?

I know other libraries like themes-switch exposes a themes global variables with a function of changeTheme.

itayganor commented 4 years ago

Closing since I have gone through major progress in it.

githoniel commented 4 years ago

you can switch theme like this

append new theme Link tag and then move old theme Link tag from html

I will explain theme load and theme switch in readme later

  private async setThemeStyleSheet() {
    const docHead = document.head
    const existedStylelinkList = Array.from(document.getElementsByTagName('link'))
      .filter((t) => t.getAttribute(Const.styleAttrKey) === Const.styleAttrValue)
    await Promise.all(this.themePaths.map((themePath) => {
      let resolve
      const p = new Promise((_resolve) => {
        resolve = _resolve
      })
      const linkDOM = document.createElement('link')
      linkDOM.setAttribute('rel', 'stylesheet')
      linkDOM.setAttribute('type', 'text/css')
      linkDOM.setAttribute('href', themePath)
      linkDOM.setAttribute(Const.styleAttrKey, Const.styleAttrValue)

      let onScriptComplete: (event) => void
      const timeout = setTimeout(() => {
        onScriptComplete({ type: 'timeout', target: linkDOM })
      }, 120000)
      onScriptComplete = () => {
        onScriptComplete = () => {}
        // avoid mem leaks in IE.
        linkDOM.onerror = null
        linkDOM.onload = null
        clearTimeout(timeout)
        resolve()
      }
      linkDOM.onerror = onScriptComplete
      linkDOM.onload = onScriptComplete
      docHead.appendChild(linkDOM)
      return p as Promise<void>
    }))

    existedStylelinkList.forEach((t) => {
      t.parentNode?.removeChild(t)
    })
  }
}