-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiframe-theme.js
More file actions
67 lines (60 loc) · 2.08 KB
/
Copy pathiframe-theme.js
File metadata and controls
67 lines (60 loc) · 2.08 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(function () {
function updateIframesForDarkMode() {
const isDark = document.documentElement.classList.contains("dark");
document.querySelectorAll('iframe[src*="chromatic.com/iframe.html"]').forEach((iframe) => {
iframe.style.background = "transparent";
iframe.allowTransparency = true;
// Use postMessage to communicate with the iframe since we can't access contentDocument due to CORS
const sendThemeMessage = () => {
try {
const message = {
type: 'THEME_CHANGE',
isDark: isDark,
styles: {
background: isDark ? '#0b0d0f' : 'transparent' // transparent for light mode
}
};
iframe.contentWindow.postMessage(message, '*');
} catch (e) {
console.warn("Could not send message to iframe:", e);
}
};
// Send message immediately if iframe might be loaded
sendThemeMessage();
// Also send message when iframe loads
iframe.addEventListener("load", () => {
// Add a small delay to ensure iframe is ready
setTimeout(sendThemeMessage, 100);
});
});
}
// Listen for theme changes on the parent document
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' &&
mutation.attributeName === 'class' &&
mutation.target === document.documentElement) {
updateIframesForDarkMode();
}
});
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class']
});
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", updateIframesForDarkMode);
} else {
setTimeout(updateIframesForDarkMode, 100);
// TODO: add Storybook with Darkmode enabled
let themeChangeCount = 0;
const themeChangeInterval = setInterval(() => {
if (themeChangeCount < 2) {
updateIframesForDarkMode();
themeChangeCount++;
} else {
clearInterval(themeChangeInterval);
}
}, 1000);
}
})();