darkify-js 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2022-present Emilio Romero
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Emilio Romero
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,29 +1,34 @@
1
- # Darkify js
2
- Create an easy dark mode for your site
3
- ## 📦 Installation
4
- ```bash
5
- npm install darkify-js
6
- ```
7
- ## ⚙️ Setup
8
- ```js
9
- import Darkify from 'darkify-js'
10
-
11
- const options = {
12
- autoMatchTheme: true,
13
- }
14
-
15
- // autoMatchTheme: default is true
16
- // useLocalStorage: default is true
17
- // useSessionStorage: default is false
18
- // useColorScheme: default is ['#ffffff', '#000000']
19
-
20
- var darkMode = new Darkify('#element', options)
21
- ```
22
- ### CDN
23
-
24
- ```html
25
- <script src="https://cdn.jsdelivr.net/npm/darkify-js"></script>
26
- ```
27
-
28
- ## Compatibility
29
- [Check browser compatibility](https://caniuse.com/mdn-css_properties_color-scheme)
1
+ # Darkify JS
2
+ [![Run tests](https://github.com/emrocode/darkify-js/actions/workflows/tests.yml/badge.svg)](https://github.com/emrocode/darkify-js/actions/workflows/tests.yml)
3
+
4
+ 🌚 A simple dark mode toggle library that makes it easy to implement dark mode on your website without additional configuration
5
+
6
+ > Please make sure to read the [Wiki] for detailed documentation and examples
7
+
8
+ ### 📦 Installation
9
+
10
+ Use npm or any other package manager:
11
+
12
+ ```bash
13
+ npm install darkify-js
14
+ ```
15
+
16
+ ### ⚙️ Setup
17
+
18
+ ```js
19
+ // main.js
20
+ import Darkify from 'darkify-js';
21
+
22
+ const options = {
23
+ autoMatchTheme: true,
24
+ };
25
+
26
+ // autoMatchTheme: default is true
27
+ // useLocalStorage: default is true
28
+ // useSessionStorage: default is false
29
+ // useColorScheme: default is ['#ffffff', '#000000']
30
+
31
+ new Darkify('#element', options);
32
+ ```
33
+
34
+ [Wiki]: https://github.com/emrocode/darkify-js/wiki
@@ -1,91 +1,114 @@
1
1
  /**
2
2
  *
3
3
  * @author Emilio Romero <emrocode@gmail.com>
4
- * @version 1.1.3
4
+ * @version 1.1.5
5
5
  * @license MIT
6
6
  */
7
7
  'use strict';
8
8
 
9
- Object.defineProperty(exports, '__esModule', { value: true });
9
+ function __classPrivateFieldGet(receiver, state, kind, f) {
10
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
11
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
12
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
13
+ }
14
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
15
+ if (kind === "m") throw new TypeError("Private method is not writable");
16
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
17
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
18
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
19
+ }
20
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
21
+ var e = new Error(message);
22
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
23
+ };
10
24
 
11
25
  const isBrowser = typeof window !== 'undefined';
26
+
27
+ const defaultOptions = {
28
+ autoMatchTheme: true,
29
+ useLocalStorage: true,
30
+ useSessionStorage: false,
31
+ useColorScheme: ['#ffffff', '#000000'],
32
+ };
33
+
34
+ var _Darkify_instances, _a, _Darkify_theme, _Darkify_cssTag, _Darkify_metaTag, _Darkify_init, _Darkify_getOsPreference, _Darkify_createAttribute, _Darkify_updateTags, _Darkify_savePreference, _Darkify_syncThemeBetweenTabs;
12
35
  class Darkify {
13
36
  constructor(element, options) {
37
+ _Darkify_instances.add(this);
14
38
  this.options = {};
15
- if (!isBrowser) {
39
+ _Darkify_theme.set(this, void 0);
40
+ _Darkify_cssTag.set(this, void 0);
41
+ _Darkify_metaTag.set(this, void 0);
42
+ if (!isBrowser)
16
43
  return;
17
- }
18
- if (options?.useLocalStorage) {
19
- options.useSessionStorage = false;
20
- }
21
- else if (options?.useSessionStorage) {
22
- options.useLocalStorage = false;
23
- }
24
- const defaultOptions = {
25
- autoMatchTheme: true,
26
- useLocalStorage: true,
27
- useSessionStorage: false,
28
- useColorScheme: ['#ffffff', '#000000'],
29
- };
30
- options = { ...defaultOptions, ...options };
44
+ (options === null || options === void 0 ? void 0 : options.useLocalStorage) && (options.useSessionStorage = false);
45
+ (options === null || options === void 0 ? void 0 : options.useSessionStorage) && (options.useLocalStorage = false);
46
+ options = Object.assign(Object.assign({}, defaultOptions), options);
31
47
  this.options = options;
32
- document.addEventListener('DOMContentLoaded', () => {
33
- this.createAttribute();
34
- const htmlElement = document.querySelector(element);
35
- htmlElement?.addEventListener('click', () => this.onClick());
36
- });
37
- window
38
- .matchMedia('(prefers-color-scheme: dark)')
39
- .addEventListener('change', ({ matches: isDark }) => {
40
- this.theme.value = isDark ? 'dark' : 'light';
41
- this.savePreference();
42
- return window.location.reload();
43
- });
44
- this.theme = {
45
- value: this.getOsPreference(options) ?? 'light',
46
- };
47
- this.cssTag = document.createElement('style');
48
- this.metaTag = document.createElement('meta');
49
- this.createAttribute();
50
- }
51
- getOsPreference(options) {
52
- const { autoMatchTheme, useLocalStorage, useSessionStorage } = options;
53
- const STO = (useLocalStorage && window.localStorage.getItem(Darkify.storageKey)) ||
54
- (useSessionStorage && window.sessionStorage.getItem(Darkify.storageKey));
55
- return (STO ||
56
- (autoMatchTheme && window.matchMedia('(prefers-color-scheme: dark)').matches
57
- ? 'dark'
58
- : 'light'));
59
- }
60
- createAttribute() {
61
- const dataTheme = document.getElementsByTagName('html')[0];
62
- const { useColorScheme } = this.options;
63
- let css = `/**! Darkify / A simple dark mode toggle library **/:root:is([data-theme="${this.theme.value}"]), [data-theme="${this.theme.value}"] {color-scheme: ${this.theme.value}}`;
64
- dataTheme.setAttribute('data-theme', this.theme.value);
65
- this.updateTags(css, useColorScheme || []);
66
- this.savePreference();
48
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_init).call(this, element);
49
+ __classPrivateFieldSet(this, _Darkify_theme, { value: __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_getOsPreference).call(this, options) }, "f");
50
+ __classPrivateFieldSet(this, _Darkify_cssTag, document.createElement('style'), "f");
51
+ __classPrivateFieldSet(this, _Darkify_metaTag, document.createElement('meta'), "f");
52
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
53
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_syncThemeBetweenTabs).call(this);
67
54
  }
68
- updateTags(css, useColorScheme) {
69
- const head = document.head;
70
- this.metaTag.setAttribute('name', 'theme-color');
71
- this.metaTag.setAttribute('content', this.theme.value === 'light' ? useColorScheme[0] : useColorScheme[1]);
72
- this.cssTag.setAttribute('type', 'text/css');
73
- this.cssTag.innerHTML = css;
74
- head.appendChild(this.metaTag);
75
- head.appendChild(this.cssTag);
55
+ toggleTheme() {
56
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = __classPrivateFieldGet(this, _Darkify_theme, "f").value === 'light' ? 'dark' : 'light';
57
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
76
58
  }
77
- savePreference() {
78
- const { useLocalStorage } = this.options;
79
- const STO = useLocalStorage ? window.localStorage : window.sessionStorage;
80
- const OTS = useLocalStorage ? window.sessionStorage : window.localStorage;
81
- OTS.removeItem(Darkify.storageKey);
82
- STO.setItem(Darkify.storageKey, this.theme.value);
83
- }
84
- onClick() {
85
- this.theme.value = this.theme.value === 'light' ? 'dark' : 'light';
86
- this.createAttribute();
59
+ getCurrentTheme() {
60
+ return __classPrivateFieldGet(this, _Darkify_theme, "f").value;
87
61
  }
88
62
  }
89
- Darkify.storageKey = 'darkify-theme';
63
+ _a = Darkify, _Darkify_theme = new WeakMap(), _Darkify_cssTag = new WeakMap(), _Darkify_metaTag = new WeakMap(), _Darkify_instances = new WeakSet(), _Darkify_init = function _Darkify_init(element) {
64
+ window
65
+ .matchMedia('(prefers-color-scheme: dark)')
66
+ .addEventListener('change', ({ matches: isDark }) => {
67
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = isDark ? 'dark' : 'light';
68
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_savePreference).call(this);
69
+ });
70
+ document.addEventListener('DOMContentLoaded', () => {
71
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
72
+ const htmlElement = document.querySelector(element);
73
+ htmlElement === null || htmlElement === void 0 ? void 0 : htmlElement.addEventListener('click', () => this.toggleTheme());
74
+ });
75
+ }, _Darkify_getOsPreference = function _Darkify_getOsPreference(options) {
76
+ const { autoMatchTheme, useLocalStorage, useSessionStorage } = options;
77
+ const STO = (useLocalStorage && window.localStorage.getItem(_a.storageKey)) ||
78
+ (useSessionStorage && window.sessionStorage.getItem(_a.storageKey));
79
+ return (STO ||
80
+ (autoMatchTheme && window.matchMedia('(prefers-color-scheme: dark)').matches
81
+ ? 'dark'
82
+ : 'light'));
83
+ }, _Darkify_createAttribute = function _Darkify_createAttribute() {
84
+ const dataTheme = document.getElementsByTagName('html')[0];
85
+ const { useColorScheme } = this.options;
86
+ let css = `/**! Darkify / A simple dark mode toggle library **/\n:root:is([data-theme="${__classPrivateFieldGet(this, _Darkify_theme, "f").value}"]),[data-theme="${__classPrivateFieldGet(this, _Darkify_theme, "f").value}"]{color-scheme:${__classPrivateFieldGet(this, _Darkify_theme, "f").value}}`;
87
+ dataTheme.setAttribute('data-theme', __classPrivateFieldGet(this, _Darkify_theme, "f").value);
88
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_updateTags).call(this, css, useColorScheme || []);
89
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_savePreference).call(this);
90
+ }, _Darkify_updateTags = function _Darkify_updateTags(css, useColorScheme) {
91
+ const head = document.head || document.getElementsByTagName('head')[0];
92
+ __classPrivateFieldGet(this, _Darkify_metaTag, "f").setAttribute('name', 'theme-color');
93
+ __classPrivateFieldGet(this, _Darkify_metaTag, "f").setAttribute('content', __classPrivateFieldGet(this, _Darkify_theme, "f").value === 'light' ? useColorScheme[0] : useColorScheme[1]);
94
+ __classPrivateFieldGet(this, _Darkify_cssTag, "f").setAttribute('type', 'text/css');
95
+ __classPrivateFieldGet(this, _Darkify_cssTag, "f").innerHTML = css;
96
+ head.appendChild(__classPrivateFieldGet(this, _Darkify_metaTag, "f"));
97
+ head.appendChild(__classPrivateFieldGet(this, _Darkify_cssTag, "f"));
98
+ }, _Darkify_savePreference = function _Darkify_savePreference() {
99
+ const { useLocalStorage } = this.options;
100
+ const STO = useLocalStorage ? window.localStorage : window.sessionStorage;
101
+ const OTS = useLocalStorage ? window.sessionStorage : window.localStorage;
102
+ OTS.removeItem(_a.storageKey);
103
+ STO.setItem(_a.storageKey, __classPrivateFieldGet(this, _Darkify_theme, "f").value);
104
+ }, _Darkify_syncThemeBetweenTabs = function _Darkify_syncThemeBetweenTabs() {
105
+ window.addEventListener('storage', (e) => {
106
+ if (e.key === 'theme' && e.newValue) {
107
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = e.newValue;
108
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
109
+ }
110
+ });
111
+ };
112
+ Darkify.storageKey = 'theme';
90
113
 
91
- exports.default = Darkify;
114
+ module.exports = Darkify;
package/dist/darkify.d.ts CHANGED
@@ -1,26 +1,30 @@
1
- type Options = {
2
- autoMatchTheme?: boolean;
3
- useLocalStorage?: boolean;
4
- useSessionStorage?: boolean;
5
- useColorScheme?: string[];
1
+ type Options = {
2
+ autoMatchTheme?: boolean;
3
+ useLocalStorage?: boolean;
4
+ useSessionStorage?: boolean;
5
+ useColorScheme?: string[];
6
6
  };
7
7
 
8
8
  declare class Darkify {
9
+ #private;
9
10
  private static readonly storageKey;
10
- private options;
11
- private theme;
12
- private cssTag;
13
- private metaTag;
11
+ readonly options: Options;
14
12
  /**
15
13
  * @param {string} element Button ID ( recommended ) or HTML element
16
14
  * @param {object} options Options
15
+ * @see {@link https://github.com/emrocode/darkify-js/wiki|Documentation}
17
16
  */
18
17
  constructor(element: string, options: Options);
19
- getOsPreference(options: Options): string;
20
- createAttribute(): void;
21
- updateTags(css: string, useColorScheme: string[]): void;
22
- savePreference(): void;
23
- onClick(): void;
18
+ /**
19
+ * Toggles the theme between light and dark modes
20
+ * @returns {void}
21
+ */
22
+ toggleTheme(): void;
23
+ /**
24
+ * Retrieves the current active theme
25
+ * @returns {string}
26
+ */
27
+ getCurrentTheme(): string;
24
28
  }
25
29
 
26
30
  export { Darkify as default };
@@ -1,87 +1,112 @@
1
1
  /**
2
2
  *
3
3
  * @author Emilio Romero <emrocode@gmail.com>
4
- * @version 1.1.3
4
+ * @version 1.1.5
5
5
  * @license MIT
6
6
  */
7
+ function __classPrivateFieldGet(receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ }
12
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
13
+ if (kind === "m") throw new TypeError("Private method is not writable");
14
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
15
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
16
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
17
+ }
18
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
19
+ var e = new Error(message);
20
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
21
+ };
22
+
7
23
  const isBrowser = typeof window !== 'undefined';
24
+
25
+ const defaultOptions = {
26
+ autoMatchTheme: true,
27
+ useLocalStorage: true,
28
+ useSessionStorage: false,
29
+ useColorScheme: ['#ffffff', '#000000'],
30
+ };
31
+
32
+ var _Darkify_instances, _a, _Darkify_theme, _Darkify_cssTag, _Darkify_metaTag, _Darkify_init, _Darkify_getOsPreference, _Darkify_createAttribute, _Darkify_updateTags, _Darkify_savePreference, _Darkify_syncThemeBetweenTabs;
8
33
  class Darkify {
9
34
  constructor(element, options) {
35
+ _Darkify_instances.add(this);
10
36
  this.options = {};
11
- if (!isBrowser) {
37
+ _Darkify_theme.set(this, void 0);
38
+ _Darkify_cssTag.set(this, void 0);
39
+ _Darkify_metaTag.set(this, void 0);
40
+ if (!isBrowser)
12
41
  return;
13
- }
14
- if (options?.useLocalStorage) {
15
- options.useSessionStorage = false;
16
- }
17
- else if (options?.useSessionStorage) {
18
- options.useLocalStorage = false;
19
- }
20
- const defaultOptions = {
21
- autoMatchTheme: true,
22
- useLocalStorage: true,
23
- useSessionStorage: false,
24
- useColorScheme: ['#ffffff', '#000000'],
25
- };
26
- options = { ...defaultOptions, ...options };
42
+ (options === null || options === void 0 ? void 0 : options.useLocalStorage) && (options.useSessionStorage = false);
43
+ (options === null || options === void 0 ? void 0 : options.useSessionStorage) && (options.useLocalStorage = false);
44
+ options = Object.assign(Object.assign({}, defaultOptions), options);
27
45
  this.options = options;
28
- document.addEventListener('DOMContentLoaded', () => {
29
- this.createAttribute();
30
- const htmlElement = document.querySelector(element);
31
- htmlElement?.addEventListener('click', () => this.onClick());
32
- });
33
- window
34
- .matchMedia('(prefers-color-scheme: dark)')
35
- .addEventListener('change', ({ matches: isDark }) => {
36
- this.theme.value = isDark ? 'dark' : 'light';
37
- this.savePreference();
38
- return window.location.reload();
39
- });
40
- this.theme = {
41
- value: this.getOsPreference(options) ?? 'light',
42
- };
43
- this.cssTag = document.createElement('style');
44
- this.metaTag = document.createElement('meta');
45
- this.createAttribute();
46
- }
47
- getOsPreference(options) {
48
- const { autoMatchTheme, useLocalStorage, useSessionStorage } = options;
49
- const STO = (useLocalStorage && window.localStorage.getItem(Darkify.storageKey)) ||
50
- (useSessionStorage && window.sessionStorage.getItem(Darkify.storageKey));
51
- return (STO ||
52
- (autoMatchTheme && window.matchMedia('(prefers-color-scheme: dark)').matches
53
- ? 'dark'
54
- : 'light'));
46
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_init).call(this, element);
47
+ __classPrivateFieldSet(this, _Darkify_theme, { value: __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_getOsPreference).call(this, options) }, "f");
48
+ __classPrivateFieldSet(this, _Darkify_cssTag, document.createElement('style'), "f");
49
+ __classPrivateFieldSet(this, _Darkify_metaTag, document.createElement('meta'), "f");
50
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
51
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_syncThemeBetweenTabs).call(this);
55
52
  }
56
- createAttribute() {
57
- const dataTheme = document.getElementsByTagName('html')[0];
58
- const { useColorScheme } = this.options;
59
- let css = `/**! Darkify / A simple dark mode toggle library **/:root:is([data-theme="${this.theme.value}"]), [data-theme="${this.theme.value}"] {color-scheme: ${this.theme.value}}`;
60
- dataTheme.setAttribute('data-theme', this.theme.value);
61
- this.updateTags(css, useColorScheme || []);
62
- this.savePreference();
53
+ toggleTheme() {
54
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = __classPrivateFieldGet(this, _Darkify_theme, "f").value === 'light' ? 'dark' : 'light';
55
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
63
56
  }
64
- updateTags(css, useColorScheme) {
65
- const head = document.head;
66
- this.metaTag.setAttribute('name', 'theme-color');
67
- this.metaTag.setAttribute('content', this.theme.value === 'light' ? useColorScheme[0] : useColorScheme[1]);
68
- this.cssTag.setAttribute('type', 'text/css');
69
- this.cssTag.innerHTML = css;
70
- head.appendChild(this.metaTag);
71
- head.appendChild(this.cssTag);
72
- }
73
- savePreference() {
74
- const { useLocalStorage } = this.options;
75
- const STO = useLocalStorage ? window.localStorage : window.sessionStorage;
76
- const OTS = useLocalStorage ? window.sessionStorage : window.localStorage;
77
- OTS.removeItem(Darkify.storageKey);
78
- STO.setItem(Darkify.storageKey, this.theme.value);
79
- }
80
- onClick() {
81
- this.theme.value = this.theme.value === 'light' ? 'dark' : 'light';
82
- this.createAttribute();
57
+ getCurrentTheme() {
58
+ return __classPrivateFieldGet(this, _Darkify_theme, "f").value;
83
59
  }
84
60
  }
85
- Darkify.storageKey = 'darkify-theme';
61
+ _a = Darkify, _Darkify_theme = new WeakMap(), _Darkify_cssTag = new WeakMap(), _Darkify_metaTag = new WeakMap(), _Darkify_instances = new WeakSet(), _Darkify_init = function _Darkify_init(element) {
62
+ window
63
+ .matchMedia('(prefers-color-scheme: dark)')
64
+ .addEventListener('change', ({ matches: isDark }) => {
65
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = isDark ? 'dark' : 'light';
66
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_savePreference).call(this);
67
+ });
68
+ document.addEventListener('DOMContentLoaded', () => {
69
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
70
+ const htmlElement = document.querySelector(element);
71
+ htmlElement === null || htmlElement === void 0 ? void 0 : htmlElement.addEventListener('click', () => this.toggleTheme());
72
+ });
73
+ }, _Darkify_getOsPreference = function _Darkify_getOsPreference(options) {
74
+ const { autoMatchTheme, useLocalStorage, useSessionStorage } = options;
75
+ const STO = (useLocalStorage && window.localStorage.getItem(_a.storageKey)) ||
76
+ (useSessionStorage && window.sessionStorage.getItem(_a.storageKey));
77
+ return (STO ||
78
+ (autoMatchTheme && window.matchMedia('(prefers-color-scheme: dark)').matches
79
+ ? 'dark'
80
+ : 'light'));
81
+ }, _Darkify_createAttribute = function _Darkify_createAttribute() {
82
+ const dataTheme = document.getElementsByTagName('html')[0];
83
+ const { useColorScheme } = this.options;
84
+ let css = `/**! Darkify / A simple dark mode toggle library **/\n:root:is([data-theme="${__classPrivateFieldGet(this, _Darkify_theme, "f").value}"]),[data-theme="${__classPrivateFieldGet(this, _Darkify_theme, "f").value}"]{color-scheme:${__classPrivateFieldGet(this, _Darkify_theme, "f").value}}`;
85
+ dataTheme.setAttribute('data-theme', __classPrivateFieldGet(this, _Darkify_theme, "f").value);
86
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_updateTags).call(this, css, useColorScheme || []);
87
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_savePreference).call(this);
88
+ }, _Darkify_updateTags = function _Darkify_updateTags(css, useColorScheme) {
89
+ const head = document.head || document.getElementsByTagName('head')[0];
90
+ __classPrivateFieldGet(this, _Darkify_metaTag, "f").setAttribute('name', 'theme-color');
91
+ __classPrivateFieldGet(this, _Darkify_metaTag, "f").setAttribute('content', __classPrivateFieldGet(this, _Darkify_theme, "f").value === 'light' ? useColorScheme[0] : useColorScheme[1]);
92
+ __classPrivateFieldGet(this, _Darkify_cssTag, "f").setAttribute('type', 'text/css');
93
+ __classPrivateFieldGet(this, _Darkify_cssTag, "f").innerHTML = css;
94
+ head.appendChild(__classPrivateFieldGet(this, _Darkify_metaTag, "f"));
95
+ head.appendChild(__classPrivateFieldGet(this, _Darkify_cssTag, "f"));
96
+ }, _Darkify_savePreference = function _Darkify_savePreference() {
97
+ const { useLocalStorage } = this.options;
98
+ const STO = useLocalStorage ? window.localStorage : window.sessionStorage;
99
+ const OTS = useLocalStorage ? window.sessionStorage : window.localStorage;
100
+ OTS.removeItem(_a.storageKey);
101
+ STO.setItem(_a.storageKey, __classPrivateFieldGet(this, _Darkify_theme, "f").value);
102
+ }, _Darkify_syncThemeBetweenTabs = function _Darkify_syncThemeBetweenTabs() {
103
+ window.addEventListener('storage', (e) => {
104
+ if (e.key === 'theme' && e.newValue) {
105
+ __classPrivateFieldGet(this, _Darkify_theme, "f").value = e.newValue;
106
+ __classPrivateFieldGet(this, _Darkify_instances, "m", _Darkify_createAttribute).call(this);
107
+ }
108
+ });
109
+ };
110
+ Darkify.storageKey = 'theme';
86
111
 
87
112
  export { Darkify as default };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  *
3
3
  * @author Emilio Romero <emrocode@gmail.com>
4
- * @version 1.1.3
4
+ * @version 1.1.5
5
5
  * @license MIT
6
6
  */
7
- var Darkify=function(){"use strict";const e="undefined"!=typeof window;class t{constructor(t,s){if(this.options={},!e)return;s?.useLocalStorage?s.useSessionStorage=!1:s?.useSessionStorage&&(s.useLocalStorage=!1);s={autoMatchTheme:!0,useLocalStorage:!0,useSessionStorage:!1,useColorScheme:["#ffffff","#000000"],...s},this.options=s,document.addEventListener("DOMContentLoaded",(()=>{this.createAttribute();const e=document.querySelector(t);e?.addEventListener("click",(()=>this.onClick()))})),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",(({matches:e})=>(this.theme.value=e?"dark":"light",this.savePreference(),window.location.reload()))),this.theme={value:this.getOsPreference(s)??"light"},this.cssTag=document.createElement("style"),this.metaTag=document.createElement("meta"),this.createAttribute()}getOsPreference(e){const{autoMatchTheme:s,useLocalStorage:a,useSessionStorage:o}=e;return a&&window.localStorage.getItem(t.storageKey)||o&&window.sessionStorage.getItem(t.storageKey)||(s&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}createAttribute(){const e=document.getElementsByTagName("html")[0],{useColorScheme:t}=this.options;let s=`/**! Darkify / A simple dark mode toggle library **/:root:is([data-theme="${this.theme.value}"]), [data-theme="${this.theme.value}"] {color-scheme: ${this.theme.value}}`;e.setAttribute("data-theme",this.theme.value),this.updateTags(s,t||[]),this.savePreference()}updateTags(e,t){const s=document.head;this.metaTag.setAttribute("name","theme-color"),this.metaTag.setAttribute("content","light"===this.theme.value?t[0]:t[1]),this.cssTag.setAttribute("type","text/css"),this.cssTag.innerHTML=e,s.appendChild(this.metaTag),s.appendChild(this.cssTag)}savePreference(){const{useLocalStorage:e}=this.options,s=e?window.localStorage:window.sessionStorage;(e?window.sessionStorage:window.localStorage).removeItem(t.storageKey),s.setItem(t.storageKey,this.theme.value)}onClick(){this.theme.value="light"===this.theme.value?"dark":"light",this.createAttribute()}}return t.storageKey="darkify-theme",t}();
7
+ var Darkify=function(){"use strict";function e(e,t,s,o){if("a"===s&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?o:"a"===s?o.call(e):o?o.value:t.get(e)}function t(e,t,s,o,a){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?a.call(e,s):a?a.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const s="undefined"!=typeof window,o={autoMatchTheme:!0,useLocalStorage:!0,useSessionStorage:!1,useColorScheme:["#ffffff","#000000"]};var a,i,r,n,h,l,c,u,d,m,f;class g{constructor(i,d){a.add(this),this.options={},r.set(this,void 0),n.set(this,void 0),h.set(this,void 0),s&&((null==d?void 0:d.useLocalStorage)&&(d.useSessionStorage=!1),(null==d?void 0:d.useSessionStorage)&&(d.useLocalStorage=!1),d=Object.assign(Object.assign({},o),d),this.options=d,e(this,a,"m",l).call(this,i),t(this,r,{value:e(this,a,"m",c).call(this,d)},"f"),t(this,n,document.createElement("style"),"f"),t(this,h,document.createElement("meta"),"f"),e(this,a,"m",u).call(this),e(this,a,"m",f).call(this))}toggleTheme(){e(this,r,"f").value="light"===e(this,r,"f").value?"dark":"light",e(this,a,"m",u).call(this)}getCurrentTheme(){return e(this,r,"f").value}}return i=g,r=new WeakMap,n=new WeakMap,h=new WeakMap,a=new WeakSet,l=function(t){window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",(({matches:t})=>{e(this,r,"f").value=t?"dark":"light",e(this,a,"m",m).call(this)})),document.addEventListener("DOMContentLoaded",(()=>{e(this,a,"m",u).call(this);const s=document.querySelector(t);null==s||s.addEventListener("click",(()=>this.toggleTheme()))}))},c=function(e){const{autoMatchTheme:t,useLocalStorage:s,useSessionStorage:o}=e;return s&&window.localStorage.getItem(i.storageKey)||o&&window.sessionStorage.getItem(i.storageKey)||(t&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")},u=function(){const t=document.getElementsByTagName("html")[0],{useColorScheme:s}=this.options;let o=`/**! Darkify / A simple dark mode toggle library **/\n:root:is([data-theme="${e(this,r,"f").value}"]),[data-theme="${e(this,r,"f").value}"]{color-scheme:${e(this,r,"f").value}}`;t.setAttribute("data-theme",e(this,r,"f").value),e(this,a,"m",d).call(this,o,s||[]),e(this,a,"m",m).call(this)},d=function(t,s){const o=document.head||document.getElementsByTagName("head")[0];e(this,h,"f").setAttribute("name","theme-color"),e(this,h,"f").setAttribute("content","light"===e(this,r,"f").value?s[0]:s[1]),e(this,n,"f").setAttribute("type","text/css"),e(this,n,"f").innerHTML=t,o.appendChild(e(this,h,"f")),o.appendChild(e(this,n,"f"))},m=function(){const{useLocalStorage:t}=this.options,s=t?window.localStorage:window.sessionStorage;(t?window.sessionStorage:window.localStorage).removeItem(i.storageKey),s.setItem(i.storageKey,e(this,r,"f").value)},f=function(){window.addEventListener("storage",(t=>{"theme"===t.key&&t.newValue&&(e(this,r,"f").value=t.newValue,e(this,a,"m",u).call(this))}))},g.storageKey="theme",g}();
@@ -1,95 +1,7 @@
1
1
  /**
2
2
  *
3
3
  * @author Emilio Romero <emrocode@gmail.com>
4
- * @version 1.1.3
4
+ * @version 1.1.5
5
5
  * @license MIT
6
6
  */
7
- (function (global, factory) {
8
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
9
- typeof define === 'function' && define.amd ? define(factory) :
10
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Darkify = factory());
11
- })(this, (function () { 'use strict';
12
-
13
- const isBrowser = typeof window !== 'undefined';
14
- class Darkify {
15
- constructor(element, options) {
16
- this.options = {};
17
- if (!isBrowser) {
18
- return;
19
- }
20
- if (options?.useLocalStorage) {
21
- options.useSessionStorage = false;
22
- }
23
- else if (options?.useSessionStorage) {
24
- options.useLocalStorage = false;
25
- }
26
- const defaultOptions = {
27
- autoMatchTheme: true,
28
- useLocalStorage: true,
29
- useSessionStorage: false,
30
- useColorScheme: ['#ffffff', '#000000'],
31
- };
32
- options = { ...defaultOptions, ...options };
33
- this.options = options;
34
- document.addEventListener('DOMContentLoaded', () => {
35
- this.createAttribute();
36
- const htmlElement = document.querySelector(element);
37
- htmlElement?.addEventListener('click', () => this.onClick());
38
- });
39
- window
40
- .matchMedia('(prefers-color-scheme: dark)')
41
- .addEventListener('change', ({ matches: isDark }) => {
42
- this.theme.value = isDark ? 'dark' : 'light';
43
- this.savePreference();
44
- return window.location.reload();
45
- });
46
- this.theme = {
47
- value: this.getOsPreference(options) ?? 'light',
48
- };
49
- this.cssTag = document.createElement('style');
50
- this.metaTag = document.createElement('meta');
51
- this.createAttribute();
52
- }
53
- getOsPreference(options) {
54
- const { autoMatchTheme, useLocalStorage, useSessionStorage } = options;
55
- const STO = (useLocalStorage && window.localStorage.getItem(Darkify.storageKey)) ||
56
- (useSessionStorage && window.sessionStorage.getItem(Darkify.storageKey));
57
- return (STO ||
58
- (autoMatchTheme && window.matchMedia('(prefers-color-scheme: dark)').matches
59
- ? 'dark'
60
- : 'light'));
61
- }
62
- createAttribute() {
63
- const dataTheme = document.getElementsByTagName('html')[0];
64
- const { useColorScheme } = this.options;
65
- let css = `/**! Darkify / A simple dark mode toggle library **/:root:is([data-theme="${this.theme.value}"]), [data-theme="${this.theme.value}"] {color-scheme: ${this.theme.value}}`;
66
- dataTheme.setAttribute('data-theme', this.theme.value);
67
- this.updateTags(css, useColorScheme || []);
68
- this.savePreference();
69
- }
70
- updateTags(css, useColorScheme) {
71
- const head = document.head;
72
- this.metaTag.setAttribute('name', 'theme-color');
73
- this.metaTag.setAttribute('content', this.theme.value === 'light' ? useColorScheme[0] : useColorScheme[1]);
74
- this.cssTag.setAttribute('type', 'text/css');
75
- this.cssTag.innerHTML = css;
76
- head.appendChild(this.metaTag);
77
- head.appendChild(this.cssTag);
78
- }
79
- savePreference() {
80
- const { useLocalStorage } = this.options;
81
- const STO = useLocalStorage ? window.localStorage : window.sessionStorage;
82
- const OTS = useLocalStorage ? window.sessionStorage : window.localStorage;
83
- OTS.removeItem(Darkify.storageKey);
84
- STO.setItem(Darkify.storageKey, this.theme.value);
85
- }
86
- onClick() {
87
- this.theme.value = this.theme.value === 'light' ? 'dark' : 'light';
88
- this.createAttribute();
89
- }
90
- }
91
- Darkify.storageKey = 'darkify-theme';
92
-
93
- return Darkify;
94
-
95
- }));
7
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Darkify=t()}(this,(function(){"use strict";function e(e,t,o,s){if("a"===o&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===o?s:"a"===o?s.call(e):s?s.value:t.get(e)}function t(e,t,o,s,i){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?i.call(e,o):i?i.value=o:t.set(e,o),o}"function"==typeof SuppressedError&&SuppressedError;const o="undefined"!=typeof window,s={autoMatchTheme:!0,useLocalStorage:!0,useSessionStorage:!1,useColorScheme:["#ffffff","#000000"]};var i,a,n,r,h,l,c,d,u,f,m;class g{constructor(a,u){i.add(this),this.options={},n.set(this,void 0),r.set(this,void 0),h.set(this,void 0),o&&((null==u?void 0:u.useLocalStorage)&&(u.useSessionStorage=!1),(null==u?void 0:u.useSessionStorage)&&(u.useLocalStorage=!1),u=Object.assign(Object.assign({},s),u),this.options=u,e(this,i,"m",l).call(this,a),t(this,n,{value:e(this,i,"m",c).call(this,u)},"f"),t(this,r,document.createElement("style"),"f"),t(this,h,document.createElement("meta"),"f"),e(this,i,"m",d).call(this),e(this,i,"m",m).call(this))}toggleTheme(){e(this,n,"f").value="light"===e(this,n,"f").value?"dark":"light",e(this,i,"m",d).call(this)}getCurrentTheme(){return e(this,n,"f").value}}return a=g,n=new WeakMap,r=new WeakMap,h=new WeakMap,i=new WeakSet,l=function(t){window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",(({matches:t})=>{e(this,n,"f").value=t?"dark":"light",e(this,i,"m",f).call(this)})),document.addEventListener("DOMContentLoaded",(()=>{e(this,i,"m",d).call(this);const o=document.querySelector(t);null==o||o.addEventListener("click",(()=>this.toggleTheme()))}))},c=function(e){const{autoMatchTheme:t,useLocalStorage:o,useSessionStorage:s}=e;return o&&window.localStorage.getItem(a.storageKey)||s&&window.sessionStorage.getItem(a.storageKey)||(t&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")},d=function(){const t=document.getElementsByTagName("html")[0],{useColorScheme:o}=this.options;let s=`/**! Darkify / A simple dark mode toggle library **/\n:root:is([data-theme="${e(this,n,"f").value}"]),[data-theme="${e(this,n,"f").value}"]{color-scheme:${e(this,n,"f").value}}`;t.setAttribute("data-theme",e(this,n,"f").value),e(this,i,"m",u).call(this,s,o||[]),e(this,i,"m",f).call(this)},u=function(t,o){const s=document.head||document.getElementsByTagName("head")[0];e(this,h,"f").setAttribute("name","theme-color"),e(this,h,"f").setAttribute("content","light"===e(this,n,"f").value?o[0]:o[1]),e(this,r,"f").setAttribute("type","text/css"),e(this,r,"f").innerHTML=t,s.appendChild(e(this,h,"f")),s.appendChild(e(this,r,"f"))},f=function(){const{useLocalStorage:t}=this.options,o=t?window.localStorage:window.sessionStorage;(t?window.sessionStorage:window.localStorage).removeItem(a.storageKey),o.setItem(a.storageKey,e(this,n,"f").value)},m=function(){window.addEventListener("storage",(t=>{"theme"===t.key&&t.newValue&&(e(this,n,"f").value=t.newValue,e(this,i,"m",d).call(this))}))},g.storageKey="theme",g}));
package/package.json CHANGED
@@ -1,49 +1,54 @@
1
- {
2
- "name": "darkify-js",
3
- "version": "1.1.3",
4
- "description": "A simple dark mode toggle library",
5
- "type": "module",
6
- "main": "dist/darkify.cjs.js",
7
- "module": "dist/darkify.esm.js",
8
- "types": "dist/darkify.d.ts",
9
- "files": [
10
- "dist/darkify.d.ts",
11
- "dist/darkify.cjs.js",
12
- "dist/darkify.esm.js",
13
- "dist/darkify.umd.js",
14
- "dist/darkify.min.js"
15
- ],
16
- "scripts": {
17
- "_cls": "rm -rf dist",
18
- "_bundle": "rollup -c rollup.config.ts --configPlugin typescript",
19
- "prettier": "prettier --write src/",
20
- "build": "npm run _cls && npm run _bundle"
21
- },
22
- "keywords": [
23
- "color-scheme",
24
- "toggle",
25
- "dark-mode",
26
- "dark-theme"
27
- ],
28
- "author": "Emilio Romero <emrocode@gmail.com>",
29
- "repository": {
30
- "type": "git",
31
- "url": "git+https://github.com/emrocode/darkify-js"
32
- },
33
- "homepage": "https://github.com/emrocode/darkify-js#readme",
34
- "bugs": {
35
- "url": "https://github.com/emrocode/darkify-js/issues"
36
- },
37
- "license": "MIT",
38
- "devDependencies": {
39
- "@rollup/plugin-commonjs": "^25.0.8",
40
- "@rollup/plugin-terser": "^0.4.4",
41
- "@rollup/plugin-typescript": "^11.1.6",
42
- "prettier": "^3.2.5",
43
- "rollup": "^4.18.0",
44
- "rollup-plugin-cleanup": "^3.2.1",
45
- "rollup-plugin-dts": "^6.1.1",
46
- "tslib": "^2.6.2",
47
- "typescript": "^5.4.5"
48
- }
49
- }
1
+ {
2
+ "name": "darkify-js",
3
+ "version": "1.1.5",
4
+ "description": "A simple dark mode toggle library",
5
+ "type": "module",
6
+ "main": "dist/darkify.cjs.js",
7
+ "module": "dist/darkify.esm.js",
8
+ "types": "dist/darkify.d.ts",
9
+ "files": [
10
+ "dist/darkify.d.ts",
11
+ "dist/darkify.cjs.js",
12
+ "dist/darkify.esm.js",
13
+ "dist/darkify.umd.js",
14
+ "dist/darkify.min.js"
15
+ ],
16
+ "scripts": {
17
+ "_cls": "rm -rf dist",
18
+ "_bundle": "rollup -c rollup.config.ts --configPlugin typescript",
19
+ "build": "npm run _cls && npm run _bundle",
20
+ "format": "prettier --write src/",
21
+ "test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/emrocode/darkify-js"
26
+ },
27
+ "keywords": [
28
+ "dark mode",
29
+ "light mode",
30
+ "theme toggle",
31
+ "dark theme",
32
+ "color scheme",
33
+ "theme switcher",
34
+ "night mode",
35
+ "automatic theme"
36
+ ],
37
+ "author": "Emilio Romero <emrocode@gmail.com>",
38
+ "license": "MIT",
39
+ "devDependencies": {
40
+ "@rollup/plugin-terser": "^0.4.4",
41
+ "@rollup/plugin-typescript": "^12.1.2",
42
+ "@types/jest": "^29.5.14",
43
+ "jest": "^29.7.0",
44
+ "jest-environment-jsdom": "^29.7.0",
45
+ "prettier": "^3.4.2",
46
+ "rollup": "^4.34.1",
47
+ "rollup-plugin-cleanup": "^3.2.1",
48
+ "rollup-plugin-dts": "^6.1.1",
49
+ "ts-jest": "^29.2.5",
50
+ "ts-node": "^10.9.2",
51
+ "tslib": "^2.8.1",
52
+ "typescript": "^5.7.3"
53
+ }
54
+ }