|
| 1 | +/* eslint-disable no-unused-vars, no-param-reassign */ |
| 2 | +import { LitElement, html, customElement } from 'lit-element'; |
| 3 | +import { store } from '../../store.js'; // connect to the Redux store. |
| 4 | +import { updateThemeMode } from '../../actions/app.js'; // redux actions needed |
| 5 | +import './pl-toggle-theme.scss?external'; |
| 6 | + |
| 7 | +@customElement('pl-toggle-theme') |
| 8 | +class ThemeToggle extends LitElement { |
| 9 | + constructor(self) { |
| 10 | + self = super(self); |
| 11 | + self.targetOrigin = |
| 12 | + window.location.protocol === 'file:' |
| 13 | + ? '*' |
| 14 | + : window.location.protocol + '//' + window.location.host; |
| 15 | + return self; |
| 16 | + } |
| 17 | + |
| 18 | + static get properties() { |
| 19 | + return { |
| 20 | + themeMode: { |
| 21 | + attribute: true, |
| 22 | + type: String, |
| 23 | + }, |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + createRenderRoot() { |
| 28 | + return this; |
| 29 | + } |
| 30 | + |
| 31 | + connectedCallback() { |
| 32 | + if (super.connectedCallback) { |
| 33 | + super.connectedCallback(); |
| 34 | + } |
| 35 | + |
| 36 | + const state = store.getState(); |
| 37 | + this.themeMode = state.app.themeMode || 'dark'; |
| 38 | + |
| 39 | + this.__storeUnsubscribe = store.subscribe(() => |
| 40 | + this._stateChanged(store.getState()) |
| 41 | + ); |
| 42 | + this._stateChanged(store.getState()); |
| 43 | + |
| 44 | + store.dispatch(updateThemeMode(this.themeMode)); |
| 45 | + } |
| 46 | + |
| 47 | + disconnectedCallback() { |
| 48 | + this.__storeUnsubscribe && this.__storeUnsubscribe(); |
| 49 | + |
| 50 | + if (super.disconnectedCallback) { |
| 51 | + super.disconnectedCallback(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + _stateChanged(state) { |
| 56 | + this.themeMode = state.app.themeMode; |
| 57 | + this.iframeElement = document.querySelector('.pl-js-iframe'); |
| 58 | + |
| 59 | + if (this.iframeElement) { |
| 60 | + const obj = JSON.stringify({ |
| 61 | + event: 'patternLab.stateChange', |
| 62 | + state, |
| 63 | + }); |
| 64 | + this.iframeElement.contentWindow.postMessage(obj, this.targetOrigin); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + render() { |
| 69 | + const toggleThemeMode = this.themeMode !== 'dark' ? 'dark' : 'light'; |
| 70 | + return html` |
| 71 | + <pl-button |
| 72 | + class="pl-c-tools__action pl-c-toggle-theme__action" |
| 73 | + title="Switch Theme" |
| 74 | + @click="${_ => store.dispatch(updateThemeMode(toggleThemeMode))}" |
| 75 | + > |
| 76 | + Switch Theme |
| 77 | +
|
| 78 | + <pl-icon slot="after" name="theme-${this.themeMode}"></pl-icon> |
| 79 | + </pl-button> |
| 80 | + `; |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +export { ThemeToggle }; |
0 commit comments