@datalayer/core
Version:
**Datalayer Core**
70 lines (69 loc) • 3.19 kB
JavaScript
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
/*
* Copyright (c) 2023-2025 Datalayer, Inc.
* Distributed under the terms of the Modified BSD License.
*/
import { useEffect, useState } from 'react';
import { BaseStyles, ThemeProvider as PrimerThemeProvider } from '@primer/react';
import { loadJupyterConfig, jupyterLabTheme } from '@datalayer/jupyter-react';
import { datalayerTheme } from '../theme';
import { useRuntimesStore } from '../state';
/**
* ThemeProvider component changing color mode with JupyterLab theme
* if embedded in Jupyter or with the browser color scheme preference.
*/
export function DatalayerThemeProvider(props) {
const { children, colorMode: colorModeProps,
// inJupyterLab,
baseStyles, ...rest } = props;
const { jupyterLabAdapter } = useRuntimesStore();
const [colorMode, setColorMode] = useState(colorModeProps ?? 'light');
const [inJupyterLab, setInJupterLab] = useState(undefined);
useEffect(() => {
setInJupterLab(loadJupyterConfig().insideJupyterLab);
}, []);
useEffect(() => {
if (inJupyterLab !== undefined) {
function colorSchemeFromMedia({ matches }) {
setColorMode(matches ? 'dark' : 'light');
}
function updateColorMode(themeManager) {
setColorMode(themeManager.theme && !themeManager.isLight(themeManager.theme) ? 'dark' : 'light');
}
if (inJupyterLab) {
// TODO remove the try/catch for JupyterLab > 4.1.
try {
const themeManager = jupyterLabAdapter?.service('@jupyterlab/apputils-extension:themes');
if (themeManager) {
updateColorMode(themeManager);
themeManager.themeChanged.connect(updateColorMode);
return () => {
themeManager.themeChanged.disconnect(updateColorMode);
};
}
}
catch (e) {
console.error('Error while setting the theme', e);
}
}
else {
colorSchemeFromMedia({
matches: window.matchMedia('(prefers-color-scheme: dark)').matches
});
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', colorSchemeFromMedia);
return () => {
window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', colorSchemeFromMedia);
};
}
}
}, [inJupyterLab, jupyterLabAdapter]);
return (inJupyterLab !== undefined ?
_jsx(PrimerThemeProvider, { colorMode: colorMode, theme: inJupyterLab ? jupyterLabTheme : datalayerTheme, ...rest, children: _jsx(BaseStyles, { style: {
backgroundColor: 'var(--bgColor-default)',
color: 'var(--fgColor-default)',
fontSize: 'var(--text-body-size-medium)',
...baseStyles
}, children: children }) })
:
_jsx(_Fragment, {}));
}