color-mode.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const color_modes = Object.freeze({
  2. DARK: "dark",
  3. LIGHT: "light",
  4. })
  5. class color_mode {
  6. #app;
  7. #current;
  8. #dark_class;
  9. #light_class;
  10. constructor(
  11. app = null,
  12. dark_class = "darkmode",
  13. light_class = "lightmode",
  14. defaults = color_modes.DARK
  15. ) {
  16. if (!(app instanceof HTMLElement)) {
  17. throw new TypeError("App to color control must be HTMLElement.");
  18. }
  19. if (typeof(dark_class) !== "string") {
  20. throw new TypeError("Name of darkmode class must be string.");
  21. }
  22. if (typeof(light_class) !== "string") {
  23. throw new TypeError("Name of lightmode class must be String.");
  24. }
  25. if (dark_class === light_class) {
  26. throw new Error("Dark modeclass and lightmode class is same.");
  27. }
  28. if (defaults !== color_modes.DARK && defaults !== color_modes.LIGHT) {
  29. throw new TypeError("Default color mode must be color modes.");
  30. }
  31. this.#current = this.#load_mode(defaults);
  32. this.#app = app;
  33. this.#dark_class = dark_class;
  34. this.#light_class = light_class;
  35. this.update();
  36. }
  37. #save_mode() {
  38. localStorage.setItem("color-mode", this.mode);
  39. }
  40. #load_mode(defaults = color_modes.DARK) {
  41. const loaded = localStorage.getItem("color-mode");
  42. if (loaded !== color_modes.DARK && loaded !== color_modes.LIGHT) {
  43. return defaults;
  44. }
  45. return loaded;
  46. }
  47. get mode() {
  48. return this.#current;
  49. }
  50. set mode(target) {
  51. if (target !== color_modes.DARK && target !== color_modes.LIGHT) {
  52. throw new TypeError("New color mode must be in color modes.");
  53. }
  54. this.#current = target;
  55. update();
  56. }
  57. reverse() {
  58. if (this.#current === color_modes.DARK) {
  59. this.#current = color_modes.LIGHT
  60. } else {
  61. this.#current = color_modes.DARK;
  62. }
  63. this.update();
  64. }
  65. update() {
  66. const app = this.#app;
  67. const darkmode = this.#dark_class;
  68. const lightmode = this.#light_class;
  69. const current = this.#current;
  70. this.#save_mode();
  71. if (app.classList.contains(darkmode)) {
  72. app.classList.remove(darkmode);
  73. }
  74. if (app.classList.contains(lightmode)) {
  75. app.classList.remove(lightmode);
  76. }
  77. if (current === color_modes.DARK) {
  78. app.classList.add(darkmode);
  79. return;
  80. }
  81. app.classList.add(lightmode);
  82. }
  83. }
  84. export { color_mode, color_modes };