color-mode.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const color_modes = Object.freeze({
  2. DARK: true,
  3. LIGHT: false,
  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 = defaults;
  32. this.#app = app;
  33. this.#dark_class = dark_class;
  34. this.#light_class = light_class;
  35. this.update();
  36. }
  37. get mode() {
  38. return this.#current;
  39. }
  40. set mode(target) {
  41. if (target !== color_modes.DARK && target !== color_modes.LIGHT) {
  42. throw new TypeError("New color mode must be in color modes.");
  43. }
  44. this.#current = target;
  45. update();
  46. }
  47. reverse(now = true) {
  48. if (this.#current === color_modes.DARK) {
  49. this.#current = color_modes.LIGHT
  50. } else {
  51. this.#current = color_modes.DARK;
  52. }
  53. if (now) {
  54. this.update();
  55. }
  56. }
  57. update() {
  58. const app = this.#app;
  59. const darkmode = this.#dark_class;
  60. const lightmode = this.#light_class;
  61. const current = this.#current;
  62. if (app.classList.contains(darkmode)) {
  63. app.classList.remove(darkmode);
  64. }
  65. if (app.classList.contains(lightmode)) {
  66. app.classList.remove(lightmode);
  67. }
  68. if (current === color_modes.DARK) {
  69. app.classList.add(darkmode);
  70. return;
  71. }
  72. if (current === color_modes.LIGHT) {
  73. app.classList.add(lightmode);
  74. }
  75. }
  76. }
  77. export { color_mode };