color_theme.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. export class color_theme {
  2. #button;
  3. #themes;
  4. get themes() {
  5. return Object.keys(this.#themes);
  6. }
  7. theme_name(target) {
  8. return this.#themes[target];
  9. }
  10. constructor(button, themes = null) {
  11. this.#button = button;
  12. this.#themes = themes;
  13. if (this.#themes === null) {
  14. this.#themes = {
  15. "dark-theme": "Dark",
  16. "white-theme": "White"
  17. };
  18. }
  19. this.#load();
  20. this.#button.addEventListener("click", () => {
  21. this.change();
  22. });
  23. }
  24. get current() {
  25. if (localStorage.hasOwnProperty("theme")) {
  26. return localStorage.getItem("theme");
  27. }
  28. return this.themes[this.themes.length - 1];
  29. }
  30. #load() {
  31. this.#show(this.current);
  32. }
  33. #save(target) {
  34. localStorage.setItem("theme", target);
  35. }
  36. #show(target) {
  37. const themes = this.themes;
  38. const body = document.querySelector("body");
  39. body.classList.forEach(count => {
  40. if (themes.indexOf(count) !== -1) {
  41. body.classList.remove(count);
  42. }
  43. });
  44. body.classList.add(target);
  45. }
  46. change() {
  47. const themes = this.themes;
  48. const current = this.current;
  49. let position = themes.indexOf(current) + 1;
  50. if (position === themes.length) {
  51. position = 0;
  52. }
  53. const updated = themes[position];
  54. this.#save(updated);
  55. this.#show(updated)
  56. }
  57. }