Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
mahozad committed Mar 11, 2022
1 parent e8f9781 commit 7fc2b96
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
19 changes: 9 additions & 10 deletions theme-switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,34 +121,33 @@ class ThemeSwitchElement extends HTMLElement {

constructor() {
super();

// See https://stackoverflow.com/q/2305654/8583692
this.shadowRoot = this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = generateIcon(...getInitialStateForIcon());

// Add the click listener to the top-most parent (the custom element itself)
// so the padding etc. on the element be also clickable
this.shadowRoot.host.addEventListener("click", () => {
const oldTheme = getUserThemeSelection();
this.toggleTheme(oldTheme);
const newTheme = getUserThemeSelection();
this.dispatchEvent(this.createEvent(oldTheme, newTheme));
});

this.shadowRoot.host.addEventListener("click", this.onClick);
// If another theme switch in page toggled, update my icon too
document.addEventListener(CUSTOM_EVENT_NAME, event => {
if (event.detail.originId !== this.identifier) {
this.adaptToTheme();
}
});

// Create some CSS to apply to the shadow DOM
// See https://css-tricks.com/styling-a-web-component/
const style = document.createElement("style");
style.textContent = generateStyle();
this.shadowRoot.append(style);
}

onClick() {
const oldTheme = getUserThemeSelection();
this.toggleTheme(oldTheme);
const newTheme = getUserThemeSelection();
const event = this.createEvent(oldTheme, newTheme);
this.dispatchEvent(event);
}

// See https://stackoverflow.com/a/53804106/8583692
createEvent(oldTheme, newTheme) {
return new CustomEvent(CUSTOM_EVENT_NAME, {
Expand Down
2 changes: 1 addition & 1 deletion theme-switch.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 7fc2b96

Please sign in to comment.