Skip to content

Commit 95a3b21

Browse files
committed
feat: refactor + convert pl-toggle-theme to lit-element
1 parent 46009d9 commit 95a3b21

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
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 };
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
@import '../../../sass/scss/core.scss';
2+
3+
pl-toggle-theme {
4+
display: flex;
5+
align-self: center;
6+
justify-content: center;
7+
align-items: center;
8+
z-index: 10;
9+
width: 100%;
10+
cursor: pointer;
11+
}
12+
13+
.pl-c-toggle-theme,
14+
.pl-c-toggle-theme__action {
15+
width: 100%;
16+
}

0 commit comments

Comments
 (0)