UNPKG

jupyterlab-theme-toggler

Version:
64 lines (63 loc) 2.42 kB
import { Switch } from '@jupyter/react-components'; import { IThemeManager, IToolbarWidgetRegistry } from '@jupyterlab/apputils'; import { ReactWidget } from '@jupyterlab/ui-components'; import { useState, useEffect } from 'react'; import * as React from 'react'; import '../style/index.css'; const themeTogglerPluginId = 'jupyterlab-theme-toggler:plugin'; const ThemeSwitch = (props) => { const { themeManager, ...others } = props; const [dark, setDark] = useState(false); const updateChecked = () => { const isDark = !themeManager.isLight(themeManager.theme); setDark(!!isDark); }; useEffect(() => { let timeout = 0; if (!themeManager.theme) { // TODO: investigate why the themeManager is undefined timeout = setTimeout(() => { updateChecked(); }, 500); } else { updateChecked(); } themeManager.themeChanged.connect(updateChecked); return () => { clearTimeout(timeout); themeManager.themeChanged.disconnect(updateChecked); }; }); return React.createElement(Switch, { ...others, "aria-checked": dark }); }; const extension = { id: themeTogglerPluginId, autoStart: true, requires: [IThemeManager], optional: [IToolbarWidgetRegistry], activate: async (app, themeManager, toolbarRegistry) => { console.log('jupyterlab-theme-toggler extension is activated!'); // Get app commands const { commands } = app; const themes = [ 'JupyterLab Light', // Light Theme goes first 'JupyterLab Dark', ]; const onChange = async () => { const isLight = themeManager.isLight(themeManager.theme); await commands.execute('apputils:change-theme', { theme: themes[~~isLight], }); }; if (toolbarRegistry) { toolbarRegistry.addFactory('TopBar', 'theme-toggler', () => { const widget = ReactWidget.create(React.createElement(ThemeSwitch, { themeManager: themeManager, onChange: onChange }, React.createElement("span", { slot: "unchecked-message" }, "Light"), React.createElement("span", { slot: "checked-message" }, "Dark"))); return widget; }); } }, }; export default extension;