-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
51 lines (46 loc) · 1.7 KB
/
Copy paththeme.js
File metadata and controls
51 lines (46 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* SPDX-FileCopyrightText: 2026 John Samuel <johnsamuelwrites@gmail.com>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
"use strict";
const THEME_KEY = 'ml-playground-theme';
const $themeToggle = document.getElementById('theme-toggle');
/**
* Apply a theme to the page. Optionally updates the editor instance
* if one is provided.
*/
export function applyTheme(theme, editorInstance) {
document.documentElement.setAttribute('data-theme', theme);
if ($themeToggle) {
$themeToggle.textContent = theme === 'dark' ? '☀️' : '🌙';
$themeToggle.setAttribute(
'aria-label',
theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'
);
}
localStorage.setItem(THEME_KEY, theme);
if (editorInstance) {
try {
if (typeof editorInstance.setTheme === 'function') editorInstance.setTheme(theme);
else if (typeof editorInstance.updateOptions === 'function') {
editorInstance.updateOptions({ theme: theme === 'dark' ? 'ml-dark' : 'ml-light' });
}
} catch (_) { /* editor not yet initialized */ }
}
}
/** Read persisted or OS-preferred theme, apply it, and return the value. */
export function initTheme() {
const stored = localStorage.getItem(THEME_KEY);
const preferred = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
const theme = stored || preferred;
applyTheme(theme); // editor not available yet — that's fine
return theme;
}
export function initThemeToggle(editorInstance) {
if (!$themeToggle) return;
$themeToggle.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme');
applyTheme(current === 'dark' ? 'light' : 'dark', editorInstance);
});
}