slicejs-web-framework 4.0.2 → 4.1.0

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.
Files changed (73) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +97 -97
  3. package/Slice/Components/Structural/ContextManager/ContextManager.js +422 -422
  4. package/Slice/Components/Structural/ContextManager/ContextManagerDebugger.js +470 -470
  5. package/Slice/Components/Structural/Controller/Controller.js +1406 -1406
  6. package/Slice/Components/Structural/Controller/allowedValuesValidation.js +52 -52
  7. package/Slice/Components/Structural/Debugger/Debugger.html +72 -72
  8. package/Slice/Components/Structural/Debugger/Debugger.js +1505 -1505
  9. package/Slice/Components/Structural/EventManager/EventManager.js +651 -651
  10. package/Slice/Components/Structural/EventManager/EventManagerDebugger.js +985 -985
  11. package/Slice/Components/Structural/LeakInspector/LeakInspector.js +296 -296
  12. package/Slice/Components/Structural/Logger/Log.js +10 -10
  13. package/Slice/Components/Structural/Logger/LogViewer/LogViewer.js +662 -662
  14. package/Slice/Components/Structural/Logger/Logger.js +225 -225
  15. package/Slice/Components/Structural/Router/Router.js +820 -810
  16. package/Slice/Components/Structural/Router/applyRouteMetadata.js +39 -0
  17. package/Slice/Components/Structural/StylesManager/StylesManager.js +82 -82
  18. package/Slice/Components/Structural/StylesManager/ThemeManager/ThemeManager.js +175 -175
  19. package/Slice/Slice.js +711 -710
  20. package/api/framework/devDepsOptimizer.js +335 -335
  21. package/api/framework/express.js +3 -3
  22. package/api/framework/precompressedStatic.js +102 -93
  23. package/api/framework/publicEnvResolver.js +123 -123
  24. package/api/framework/securityMiddleware.js +197 -197
  25. package/api/framework/seo.js +387 -0
  26. package/api/framework/server.js +777 -410
  27. package/api/index.js +14 -4
  28. package/package.json +6 -2
  29. package/sliceConfig.schema.json +122 -122
  30. package/src/App/index.html +69 -69
  31. package/src/App/index.js +20 -20
  32. package/src/App/style.css +11 -11
  33. package/src/Components/AppComponents/AboutSection/AboutSection.css +9 -9
  34. package/src/Components/AppComponents/AboutSection/AboutSection.html +8 -8
  35. package/src/Components/AppComponents/AboutSection/AboutSection.js +12 -12
  36. package/src/Components/AppComponents/AppShell/AppShell.css +10 -10
  37. package/src/Components/AppComponents/AppShell/AppShell.html +4 -4
  38. package/src/Components/AppComponents/AppShell/AppShell.js +36 -36
  39. package/src/Components/AppComponents/HomeSection/HomeSection.css +20 -20
  40. package/src/Components/AppComponents/HomeSection/HomeSection.html +10 -10
  41. package/src/Components/AppComponents/HomeSection/HomeSection.js +19 -19
  42. package/src/Components/components.js +8 -8
  43. package/src/public/Styles/sliceStyles.css +34 -34
  44. package/src/public/Themes/Dark.css +42 -42
  45. package/src/public/Themes/Light.css +31 -31
  46. package/src/public/Themes/Slice.css +47 -47
  47. package/src/public/manifest.json +15 -15
  48. package/src/public/robots.txt +4 -4
  49. package/src/public/sitemap.xml +8 -8
  50. package/src/routes.js +9 -9
  51. package/src/sliceConfig.json +72 -72
  52. package/types/index.d.ts +219 -219
  53. package/.opencode/opencode.json +0 -15
  54. package/Slice/tests/build-bundled-component-without-category.test.js +0 -103
  55. package/Slice/tests/build-js-only-visual-components.test.js +0 -144
  56. package/Slice/tests/build-singleton.test.js +0 -244
  57. package/Slice/tests/bundle-v2-runtime-contract.test.js +0 -747
  58. package/Slice/tests/context-patch-use.test.js +0 -95
  59. package/Slice/tests/destroy-cascade.test.js +0 -215
  60. package/Slice/tests/event-emitters.test.js +0 -79
  61. package/Slice/tests/event-registry.test.js +0 -141
  62. package/Slice/tests/fixtures/real-runtime-loader.mjs +0 -21
  63. package/Slice/tests/leak-orphans.test.js +0 -131
  64. package/Slice/tests/props-allowed-values-validation.test.js +0 -119
  65. package/Slice/tests/public-env-runtime-accessors.test.js +0 -44
  66. package/Slice/tests/public-env-typed-accessors.test.js +0 -66
  67. package/Slice/tests/router-loading-finally.test.js +0 -68
  68. package/api/tests/dev-deps-optimizer.test.js +0 -137
  69. package/api/tests/dev-server-external.test.js +0 -56
  70. package/api/tests/precompressed-static.test.js +0 -119
  71. package/api/tests/public-env-resolver.test.js +0 -193
  72. package/tests/router-build-failure.test.js +0 -125
  73. package/tests/router-emit-ordering.test.js +0 -63
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Apply a route's `metadata` to the document head.
3
+ *
4
+ * Only what the route declares is touched. A route without `metadata.title`
5
+ * keeps whatever the server sent: with native SEO the prerendered HTML already
6
+ * carries the right title, and writing a generic one here would undo it.
7
+ *
8
+ * `canonical` and `robots` are deliberately **never** written from here.
9
+ * Crawlers do not run this code, so rewriting them client-side could only
10
+ * desync the SPA from the HTML that was actually served.
11
+ *
12
+ * @param {Object|null} metadata route metadata (`metadata.title`, ...)
13
+ * @param {Document|null} doc injectable for tests
14
+ * @returns {void}
15
+ */
16
+ export function applyRouteMetadata(metadata, doc = typeof document !== 'undefined' ? document : null) {
17
+ if (!doc || !metadata || typeof metadata !== 'object') return;
18
+
19
+ const { title, titleTemplate, description } = metadata;
20
+
21
+ if (title) {
22
+ const next = titleTemplate && titleTemplate !== '%s'
23
+ ? titleTemplate.replace('%s', String(title))
24
+ : String(title);
25
+ if (doc.title !== next) doc.title = next;
26
+ }
27
+
28
+ if (description) {
29
+ let meta = doc.querySelector('meta[name="description"]');
30
+ if (!meta) {
31
+ meta = doc.createElement('meta');
32
+ meta.setAttribute('name', 'description');
33
+ doc.head.appendChild(meta);
34
+ }
35
+ if (meta.getAttribute('content') !== description) {
36
+ meta.setAttribute('content', description);
37
+ }
38
+ }
39
+ }
@@ -1,82 +1,82 @@
1
-
2
- export default class StylesManager {
3
- constructor() {
4
- this.componentStyles = document.createElement('style');
5
- this.componentStyles.id = 'slice-component-styles';
6
- document.head.appendChild(this.componentStyles);
7
-
8
- }
9
-
10
- /**
11
- * Load global styles and initialize ThemeManager if enabled.
12
- * @returns {Promise<void>}
13
- */
14
- async init() {
15
- const requestedStyles = Array.isArray(slice.stylesConfig.requestedStyles)
16
- ? slice.stylesConfig.requestedStyles
17
- : [];
18
-
19
- const styleResults = await Promise.all(
20
- requestedStyles.map(async (styleName) => {
21
- const styles = await slice.controller.fetchText(styleName, 'styles');
22
- return { styleName, styles };
23
- })
24
- );
25
-
26
- for (const { styleName, styles } of styleResults) {
27
- this.appendComponentStyles(styles);
28
- slice.logger.logInfo('StylesManager', `${styleName} styles loaded`);
29
- }
30
-
31
- if (slice.themeConfig.enabled) {
32
- const ThemeManagerClass = slice.frameworkClasses?.ThemeManager
33
- || await slice.getClass(`${slice.paths.structuralComponentFolderPath}/StylesManager/ThemeManager/ThemeManager.js`);
34
- if (!ThemeManagerClass) {
35
- throw new Error('ThemeManager not available');
36
- }
37
-
38
- this.themeManager = new ThemeManagerClass();
39
- let theme;
40
-
41
- if (slice.themeConfig.saveThemeLocally) {
42
- theme = localStorage.getItem('sliceTheme');
43
- }
44
-
45
- if (!theme) {
46
- theme = slice.themeConfig.defaultTheme;
47
- }
48
-
49
- if (slice.themeConfig.useBrowserTheme) {
50
- const browserTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'Dark' : 'Light';
51
- theme = browserTheme;
52
- }
53
-
54
- await this.themeManager.applyTheme(theme);
55
- }
56
- }
57
-
58
- //add a method that will add css as text to the componentStyles element
59
- /**
60
- * Append raw CSS to the global component style tag.
61
- * @param {string} cssText
62
- * @returns {void}
63
- */
64
- appendComponentStyles(cssText) {
65
- this.componentStyles.appendChild(document.createTextNode(cssText));
66
- }
67
-
68
- /**
69
- * Register CSS for a component.
70
- * @param {string} componentName
71
- * @param {string} cssText
72
- * @returns {void}
73
- */
74
- registerComponentStyles(componentName, cssText) {
75
- // Idempotent: a component's CSS is injected at most once, no matter how many
76
- // times it is built or how a caller reaches here (Controller guards upstream,
77
- // but the debuggers and the resource loader do not).
78
- if (slice.controller.requestedStyles.has(componentName)) return;
79
- slice.controller.requestedStyles.add(componentName);
80
- this.appendComponentStyles(cssText);
81
- }
82
- }
1
+
2
+ export default class StylesManager {
3
+ constructor() {
4
+ this.componentStyles = document.createElement('style');
5
+ this.componentStyles.id = 'slice-component-styles';
6
+ document.head.appendChild(this.componentStyles);
7
+
8
+ }
9
+
10
+ /**
11
+ * Load global styles and initialize ThemeManager if enabled.
12
+ * @returns {Promise<void>}
13
+ */
14
+ async init() {
15
+ const requestedStyles = Array.isArray(slice.stylesConfig.requestedStyles)
16
+ ? slice.stylesConfig.requestedStyles
17
+ : [];
18
+
19
+ const styleResults = await Promise.all(
20
+ requestedStyles.map(async (styleName) => {
21
+ const styles = await slice.controller.fetchText(styleName, 'styles');
22
+ return { styleName, styles };
23
+ })
24
+ );
25
+
26
+ for (const { styleName, styles } of styleResults) {
27
+ this.appendComponentStyles(styles);
28
+ slice.logger.logInfo('StylesManager', `${styleName} styles loaded`);
29
+ }
30
+
31
+ if (slice.themeConfig.enabled) {
32
+ const ThemeManagerClass = slice.frameworkClasses?.ThemeManager
33
+ || await slice.getClass(`${slice.paths.structuralComponentFolderPath}/StylesManager/ThemeManager/ThemeManager.js`);
34
+ if (!ThemeManagerClass) {
35
+ throw new Error('ThemeManager not available');
36
+ }
37
+
38
+ this.themeManager = new ThemeManagerClass();
39
+ let theme;
40
+
41
+ if (slice.themeConfig.saveThemeLocally) {
42
+ theme = localStorage.getItem('sliceTheme');
43
+ }
44
+
45
+ if (!theme) {
46
+ theme = slice.themeConfig.defaultTheme;
47
+ }
48
+
49
+ if (slice.themeConfig.useBrowserTheme) {
50
+ const browserTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'Dark' : 'Light';
51
+ theme = browserTheme;
52
+ }
53
+
54
+ await this.themeManager.applyTheme(theme);
55
+ }
56
+ }
57
+
58
+ //add a method that will add css as text to the componentStyles element
59
+ /**
60
+ * Append raw CSS to the global component style tag.
61
+ * @param {string} cssText
62
+ * @returns {void}
63
+ */
64
+ appendComponentStyles(cssText) {
65
+ this.componentStyles.appendChild(document.createTextNode(cssText));
66
+ }
67
+
68
+ /**
69
+ * Register CSS for a component.
70
+ * @param {string} componentName
71
+ * @param {string} cssText
72
+ * @returns {void}
73
+ */
74
+ registerComponentStyles(componentName, cssText) {
75
+ // Idempotent: a component's CSS is injected at most once, no matter how many
76
+ // times it is built or how a caller reaches here (Controller guards upstream,
77
+ // but the debuggers and the resource loader do not).
78
+ if (slice.controller.requestedStyles.has(componentName)) return;
79
+ slice.controller.requestedStyles.add(componentName);
80
+ this.appendComponentStyles(cssText);
81
+ }
82
+ }
@@ -1,175 +1,175 @@
1
- /**
2
- * Manages theme CSS loading and persistence.
3
- */
4
- export default class ThemeManager {
5
- constructor() {
6
- this.themeStyles = new Map();
7
- this.currentTheme = null;
8
- // In-flight loads, keyed by theme name, so concurrent applyTheme() calls for
9
- // the same theme share one fetch instead of racing and double-fetching.
10
- this._loadingThemes = new Map();
11
- this.themeStyle = document.createElement('style');
12
- document.head.appendChild(this.themeStyle);
13
- }
14
-
15
- /**
16
- * Apply a theme by name.
17
- * @param {string} themeName
18
- * @returns {Promise<void>}
19
- */
20
- async applyTheme(themeName) {
21
- if (!themeName) {
22
- slice.logger.logError('ThemeManager', 'Invalid theme name');
23
- return;
24
- }
25
-
26
- // Already the active theme — nothing to re-inject.
27
- if (themeName === this.currentTheme) {
28
- return;
29
- }
30
-
31
- if (this.themeStyles.has(themeName)) {
32
- this.setThemeStyle(themeName);
33
- this.saveThemeLocally(themeName, this.themeStyles.get(themeName));
34
- return;
35
- }
36
-
37
- // Coalesce concurrent loads of the same theme into a single fetch.
38
- if (!this._loadingThemes.has(themeName)) {
39
- this._loadingThemes.set(
40
- themeName,
41
- this.loadThemeCSS(themeName).finally(() => this._loadingThemes.delete(themeName))
42
- );
43
- }
44
- await this._loadingThemes.get(themeName);
45
- }
46
-
47
- /**
48
- * Load theme CSS and cache it.
49
- * @param {string} themeName
50
- * @returns {Promise<void>}
51
- */
52
- async loadThemeCSS(themeName) {
53
- let themeContent = localStorage.getItem(`sliceTheme-${themeName}`);
54
-
55
- if (!themeContent) {
56
- try {
57
- themeContent = await slice.controller.fetchText(themeName, 'theme');
58
- } catch (error) {
59
- // A theme that fails to fetch must not abort framework init.
60
- // applyTheme() is awaited from StylesManager.init(), which runs
61
- // inside Slice.js init() — letting this throw leaves the runtime
62
- // half-built (no slice.router). An unstyled app is recoverable;
63
- // no app at all is not. fetchText already logged the cause.
64
- slice.logger.logError('ThemeManager', `Failed to load theme: ${themeName}`, error);
65
- return;
66
- }
67
- }
68
-
69
- if (!themeContent) {
70
- slice.logger.logError('ThemeManager', `Failed to load theme: ${themeName}`);
71
- return;
72
- }
73
-
74
- this.themeStyles.set(themeName, themeContent);
75
- this.setThemeStyle(themeName);
76
- this.saveThemeLocally(themeName, themeContent);
77
- }
78
-
79
- /**
80
- * Persist a theme in localStorage when enabled.
81
- * @param {string} themeName
82
- * @param {string} themeContent
83
- * @returns {void}
84
- */
85
- saveThemeLocally(themeName, themeContent) {
86
- if (slice.themeConfig.saveThemeLocally) {
87
- localStorage.setItem('sliceTheme', themeName);
88
- localStorage.setItem(`sliceTheme-${themeName}`, themeContent);
89
- slice.logger.logInfo('ThemeManager', `Theme ${themeName} saved locally`);
90
- }
91
- }
92
-
93
- /**
94
- * Clear currently applied theme styles.
95
- * @returns {void}
96
- */
97
- removeCurrentTheme() {
98
- if (this.currentTheme) {
99
- this.themeStyle.textContent = '';
100
- }
101
- }
102
-
103
- /**
104
- * Set theme style text and mark current theme.
105
- * @param {string} themeName
106
- * @returns {void}
107
- */
108
- setThemeStyle(themeName) {
109
- this.themeStyle.textContent = this.themeStyles.get(themeName);
110
- this.currentTheme = themeName;
111
- // Expose the active theme on the root element so CSS can react per theme
112
- // without any JS — e.g. [data-slice-theme="Dark"] .logo { filter: ... }.
113
- // Non-breaking: apps opt in only if they reference the attribute.
114
- if (typeof document !== 'undefined' && document.documentElement) {
115
- document.documentElement.setAttribute('data-slice-theme', themeName);
116
- }
117
- this._syncThemeColor();
118
- slice.logger.logInfo('ThemeManager', `Theme ${themeName} applied`);
119
- }
120
-
121
- /**
122
- * Sync <meta name="theme-color"> to the theme's primary background color.
123
- * Reads the CSS variable --primary-background-color from computed styles.
124
- * @returns {void}
125
- */
126
- /**
127
- * Sync <meta name="theme-color"> and <meta name="color-scheme">
128
- * from --primary-background-color (the active theme's body bg).
129
- * @returns {void}
130
- */
131
- _syncThemeColor() {
132
- if (typeof document === 'undefined') return;
133
- const bg = getComputedStyle(document.documentElement)
134
- .getPropertyValue('--primary-background-color').trim();
135
- if (!bg) return;
136
-
137
- let meta = document.querySelector('meta[name="theme-color"]');
138
- if (!meta) {
139
- meta = document.createElement('meta');
140
- meta.name = 'theme-color';
141
- document.head.appendChild(meta);
142
- }
143
- meta.content = bg;
144
-
145
- const scheme = this._isLightColor(bg) ? 'light' : 'dark';
146
- let cs = document.querySelector('meta[name="color-scheme"]');
147
- if (!cs) {
148
- cs = document.createElement('meta');
149
- cs.name = 'color-scheme';
150
- document.head.appendChild(cs);
151
- }
152
- cs.content = scheme;
153
- }
154
-
155
- /**
156
- * Rough luminance check for a hex color.
157
- * Returns true when the color is perceived as light.
158
- * @param {string} color hex (#fff / #282828)
159
- * @returns {boolean}
160
- */
161
- _isLightColor(color) {
162
- const hex = color.replace('#', '');
163
- let r, g, b;
164
- if (hex.length <= 3) {
165
- r = parseInt(hex[0] + hex[0], 16);
166
- g = parseInt(hex[1] + hex[1], 16);
167
- b = parseInt(hex[2] + hex[2], 16);
168
- } else {
169
- r = parseInt(hex.slice(0, 2), 16);
170
- g = parseInt(hex.slice(2, 4), 16);
171
- b = parseInt(hex.slice(4, 6), 16);
172
- }
173
- return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.5;
174
- }
175
- }
1
+ /**
2
+ * Manages theme CSS loading and persistence.
3
+ */
4
+ export default class ThemeManager {
5
+ constructor() {
6
+ this.themeStyles = new Map();
7
+ this.currentTheme = null;
8
+ // In-flight loads, keyed by theme name, so concurrent applyTheme() calls for
9
+ // the same theme share one fetch instead of racing and double-fetching.
10
+ this._loadingThemes = new Map();
11
+ this.themeStyle = document.createElement('style');
12
+ document.head.appendChild(this.themeStyle);
13
+ }
14
+
15
+ /**
16
+ * Apply a theme by name.
17
+ * @param {string} themeName
18
+ * @returns {Promise<void>}
19
+ */
20
+ async applyTheme(themeName) {
21
+ if (!themeName) {
22
+ slice.logger.logError('ThemeManager', 'Invalid theme name');
23
+ return;
24
+ }
25
+
26
+ // Already the active theme — nothing to re-inject.
27
+ if (themeName === this.currentTheme) {
28
+ return;
29
+ }
30
+
31
+ if (this.themeStyles.has(themeName)) {
32
+ this.setThemeStyle(themeName);
33
+ this.saveThemeLocally(themeName, this.themeStyles.get(themeName));
34
+ return;
35
+ }
36
+
37
+ // Coalesce concurrent loads of the same theme into a single fetch.
38
+ if (!this._loadingThemes.has(themeName)) {
39
+ this._loadingThemes.set(
40
+ themeName,
41
+ this.loadThemeCSS(themeName).finally(() => this._loadingThemes.delete(themeName))
42
+ );
43
+ }
44
+ await this._loadingThemes.get(themeName);
45
+ }
46
+
47
+ /**
48
+ * Load theme CSS and cache it.
49
+ * @param {string} themeName
50
+ * @returns {Promise<void>}
51
+ */
52
+ async loadThemeCSS(themeName) {
53
+ let themeContent = localStorage.getItem(`sliceTheme-${themeName}`);
54
+
55
+ if (!themeContent) {
56
+ try {
57
+ themeContent = await slice.controller.fetchText(themeName, 'theme');
58
+ } catch (error) {
59
+ // A theme that fails to fetch must not abort framework init.
60
+ // applyTheme() is awaited from StylesManager.init(), which runs
61
+ // inside Slice.js init() — letting this throw leaves the runtime
62
+ // half-built (no slice.router). An unstyled app is recoverable;
63
+ // no app at all is not. fetchText already logged the cause.
64
+ slice.logger.logError('ThemeManager', `Failed to load theme: ${themeName}`, error);
65
+ return;
66
+ }
67
+ }
68
+
69
+ if (!themeContent) {
70
+ slice.logger.logError('ThemeManager', `Failed to load theme: ${themeName}`);
71
+ return;
72
+ }
73
+
74
+ this.themeStyles.set(themeName, themeContent);
75
+ this.setThemeStyle(themeName);
76
+ this.saveThemeLocally(themeName, themeContent);
77
+ }
78
+
79
+ /**
80
+ * Persist a theme in localStorage when enabled.
81
+ * @param {string} themeName
82
+ * @param {string} themeContent
83
+ * @returns {void}
84
+ */
85
+ saveThemeLocally(themeName, themeContent) {
86
+ if (slice.themeConfig.saveThemeLocally) {
87
+ localStorage.setItem('sliceTheme', themeName);
88
+ localStorage.setItem(`sliceTheme-${themeName}`, themeContent);
89
+ slice.logger.logInfo('ThemeManager', `Theme ${themeName} saved locally`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Clear currently applied theme styles.
95
+ * @returns {void}
96
+ */
97
+ removeCurrentTheme() {
98
+ if (this.currentTheme) {
99
+ this.themeStyle.textContent = '';
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Set theme style text and mark current theme.
105
+ * @param {string} themeName
106
+ * @returns {void}
107
+ */
108
+ setThemeStyle(themeName) {
109
+ this.themeStyle.textContent = this.themeStyles.get(themeName);
110
+ this.currentTheme = themeName;
111
+ // Expose the active theme on the root element so CSS can react per theme
112
+ // without any JS — e.g. [data-slice-theme="Dark"] .logo { filter: ... }.
113
+ // Non-breaking: apps opt in only if they reference the attribute.
114
+ if (typeof document !== 'undefined' && document.documentElement) {
115
+ document.documentElement.setAttribute('data-slice-theme', themeName);
116
+ }
117
+ this._syncThemeColor();
118
+ slice.logger.logInfo('ThemeManager', `Theme ${themeName} applied`);
119
+ }
120
+
121
+ /**
122
+ * Sync <meta name="theme-color"> to the theme's primary background color.
123
+ * Reads the CSS variable --primary-background-color from computed styles.
124
+ * @returns {void}
125
+ */
126
+ /**
127
+ * Sync <meta name="theme-color"> and <meta name="color-scheme">
128
+ * from --primary-background-color (the active theme's body bg).
129
+ * @returns {void}
130
+ */
131
+ _syncThemeColor() {
132
+ if (typeof document === 'undefined') return;
133
+ const bg = getComputedStyle(document.documentElement)
134
+ .getPropertyValue('--primary-background-color').trim();
135
+ if (!bg) return;
136
+
137
+ let meta = document.querySelector('meta[name="theme-color"]');
138
+ if (!meta) {
139
+ meta = document.createElement('meta');
140
+ meta.name = 'theme-color';
141
+ document.head.appendChild(meta);
142
+ }
143
+ meta.content = bg;
144
+
145
+ const scheme = this._isLightColor(bg) ? 'light' : 'dark';
146
+ let cs = document.querySelector('meta[name="color-scheme"]');
147
+ if (!cs) {
148
+ cs = document.createElement('meta');
149
+ cs.name = 'color-scheme';
150
+ document.head.appendChild(cs);
151
+ }
152
+ cs.content = scheme;
153
+ }
154
+
155
+ /**
156
+ * Rough luminance check for a hex color.
157
+ * Returns true when the color is perceived as light.
158
+ * @param {string} color hex (#fff / #282828)
159
+ * @returns {boolean}
160
+ */
161
+ _isLightColor(color) {
162
+ const hex = color.replace('#', '');
163
+ let r, g, b;
164
+ if (hex.length <= 3) {
165
+ r = parseInt(hex[0] + hex[0], 16);
166
+ g = parseInt(hex[1] + hex[1], 16);
167
+ b = parseInt(hex[2] + hex[2], 16);
168
+ } else {
169
+ r = parseInt(hex.slice(0, 2), 16);
170
+ g = parseInt(hex.slice(2, 4), 16);
171
+ b = parseInt(hex.slice(4, 6), 16);
172
+ }
173
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.5;
174
+ }
175
+ }