thememanager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { IChangedArgs, ISettingRegistry, URLExt } from '@jupyterlab/coreutils';
  4. import { each } from '@phosphor/algorithm';
  5. import { DisposableDelegate, IDisposable } from '@phosphor/disposable';
  6. import { Widget } from '@phosphor/widgets';
  7. import { ISignal, Signal } from '@phosphor/signaling';
  8. import { Dialog, showDialog } from './dialog';
  9. import { ISplashScreen } from './splash';
  10. import { IThemeManager } from './tokens';
  11. /**
  12. * The number of milliseconds between theme loading attempts.
  13. */
  14. const REQUEST_INTERVAL = 75;
  15. /**
  16. * The number of times to attempt to load a theme before giving up.
  17. */
  18. const REQUEST_THRESHOLD = 20;
  19. type Dict<T> = { [key: string]: T };
  20. /**
  21. * A class that provides theme management.
  22. */
  23. export class ThemeManager implements IThemeManager {
  24. /**
  25. * Construct a new theme manager.
  26. */
  27. constructor(options: ThemeManager.IOptions) {
  28. const { host, key, splash, url } = options;
  29. const registry = options.settings;
  30. this._base = url;
  31. this._host = host;
  32. this._splash = splash || null;
  33. void registry.load(key).then(settings => {
  34. this._settings = settings;
  35. this._settings.changed.connect(this._loadSettings, this);
  36. this._loadSettings();
  37. });
  38. }
  39. /**
  40. * Get the name of the current theme.
  41. */
  42. get theme(): string | null {
  43. return this._current;
  44. }
  45. /**
  46. * The names of the registered themes.
  47. */
  48. get themes(): ReadonlyArray<string> {
  49. return Object.keys(this._themes);
  50. }
  51. /**
  52. * A signal fired when the application theme changes.
  53. */
  54. get themeChanged(): ISignal<this, IChangedArgs<string>> {
  55. return this._themeChanged;
  56. }
  57. /**
  58. * Get the value of a CSS variable from its key.
  59. *
  60. * @param key - A Jupyterlab CSS variable, without the leading '--jp-'.
  61. */
  62. getCSS(key: string): string {
  63. return getComputedStyle(document.documentElement).getPropertyValue(
  64. `--jp-${key}`
  65. );
  66. }
  67. /**
  68. * Load a theme CSS file by path.
  69. *
  70. * @param path - The path of the file to load.
  71. */
  72. loadCSS(path: string): Promise<void> {
  73. const base = this._base;
  74. const href = URLExt.isLocal(path) ? URLExt.join(base, path) : path;
  75. const links = this._links;
  76. return new Promise((resolve, reject) => {
  77. const link = document.createElement('link');
  78. link.setAttribute('rel', 'stylesheet');
  79. link.setAttribute('type', 'text/css');
  80. link.setAttribute('href', href);
  81. link.addEventListener('load', () => {
  82. resolve(undefined);
  83. });
  84. link.addEventListener('error', () => {
  85. reject(`Stylesheet failed to load: ${href}`);
  86. });
  87. document.body.appendChild(link);
  88. links.push(link);
  89. });
  90. }
  91. /**
  92. * Loads all current CSS overrides from settings. If an override has been
  93. * removed or is invalid, this function unloads it instead.
  94. */
  95. loadCSSOverrides(): void {
  96. const newOverrides =
  97. (this._settings.user['overrides'] as Dict<string>) || {};
  98. // iterate over the union of current and new CSS override keys
  99. Object.keys({ ...this._overrides, ...newOverrides }).forEach(key => {
  100. const val = newOverrides[key];
  101. if (val && ThemeManager.validateCSS(key, val)) {
  102. // validation succeeded, set the override
  103. document.documentElement.style.setProperty(`--jp-${key}`, val);
  104. } else {
  105. // if key is not present or validation failed, the override will be removed
  106. document.documentElement.style.removeProperty(`--jp-${key}`);
  107. }
  108. });
  109. // replace the current overrides with the new ones
  110. this._overrides = newOverrides;
  111. }
  112. /**
  113. * Register a theme with the theme manager.
  114. *
  115. * @param theme - The theme to register.
  116. *
  117. * @returns A disposable that can be used to unregister the theme.
  118. */
  119. register(theme: IThemeManager.ITheme): IDisposable {
  120. const { name } = theme;
  121. const themes = this._themes;
  122. if (themes[name]) {
  123. throw new Error(`Theme already registered for ${name}`);
  124. }
  125. themes[name] = theme;
  126. return new DisposableDelegate(() => {
  127. delete themes[name];
  128. });
  129. }
  130. /**
  131. * Add a CSS override to the settings.
  132. */
  133. setCSSOverride(key: string, value: string): Promise<void> {
  134. this._overrides[key] = value;
  135. return this._settings.set('overrides', this._overrides);
  136. }
  137. /**
  138. * Set the current theme.
  139. */
  140. setTheme(name: string): Promise<void> {
  141. return this._settings.set('theme', name);
  142. }
  143. /**
  144. * Test whether a given theme is light.
  145. */
  146. isLight(name: string): boolean {
  147. return this._themes[name].isLight;
  148. }
  149. /**
  150. * Increase a font size w.r.t. its current setting or its value in the
  151. * current theme.
  152. *
  153. * @param key - A Jupyterlab font size CSS variable, without the leading '--jp-'.
  154. */
  155. incrFontSize(key: string): Promise<void> {
  156. return this._incrFontSize(key, true);
  157. }
  158. /**
  159. * Decrease a font size w.r.t. its current setting or its value in the
  160. * current theme.
  161. *
  162. * @param key - A Jupyterlab font size CSS variable, without the leading '--jp-'.
  163. */
  164. decrFontSize(key: string): Promise<void> {
  165. return this._incrFontSize(key, false);
  166. }
  167. /**
  168. * Test whether a given theme styles scrollbars,
  169. * and if the user has scrollbar styling enabled.
  170. */
  171. themeScrollbars(name: string): boolean {
  172. return (
  173. !!this._settings.composite['theme-scrollbars'] &&
  174. !!this._themes[name].themeScrollbars
  175. );
  176. }
  177. /**
  178. * Toggle the `theme-scrollbbars` setting.
  179. */
  180. toggleThemeScrollbars(): Promise<void> {
  181. return this._settings.set(
  182. 'theme-scrollbars',
  183. !this._settings.composite['theme-scrollbars']
  184. );
  185. }
  186. /**
  187. * Change a font size by a positive or negative increment.
  188. */
  189. private _incrFontSize(key: string, add: boolean = true): Promise<void> {
  190. // get the numeric and unit parts of the current font size
  191. const parts = (this.getCSS(key) || '13px').split(/([a-zA-Z]+)/);
  192. // determine the increment
  193. const incr = (add ? 1 : -1) * (parts[1] === 'em' ? 0.1 : 1);
  194. // increment the font size and set it as an override
  195. return this.setCSSOverride(key, `${Number(parts[0]) + incr}${parts[1]}`);
  196. }
  197. /**
  198. * Handle the current settings.
  199. */
  200. private _loadSettings(): void {
  201. const outstanding = this._outstanding;
  202. const pending = this._pending;
  203. const requests = this._requests;
  204. // If another request is pending, cancel it.
  205. if (pending) {
  206. window.clearTimeout(pending);
  207. this._pending = 0;
  208. }
  209. const settings = this._settings;
  210. const themes = this._themes;
  211. const theme = settings.composite['theme'] as string;
  212. // If another promise is outstanding, wait until it finishes before
  213. // attempting to load the settings. Because outstanding promises cannot
  214. // be aborted, the order in which they occur must be enforced.
  215. if (outstanding) {
  216. outstanding
  217. .then(() => {
  218. this._loadSettings();
  219. })
  220. .catch(() => {
  221. this._loadSettings();
  222. });
  223. this._outstanding = null;
  224. return;
  225. }
  226. // Increment the request counter.
  227. requests[theme] = requests[theme] ? requests[theme] + 1 : 1;
  228. // If the theme exists, load it right away.
  229. if (themes[theme]) {
  230. this._outstanding = this._loadTheme(theme);
  231. delete requests[theme];
  232. return;
  233. }
  234. // If the request has taken too long, give up.
  235. if (requests[theme] > REQUEST_THRESHOLD) {
  236. const fallback = settings.default('theme') as string;
  237. // Stop tracking the requests for this theme.
  238. delete requests[theme];
  239. if (!themes[fallback]) {
  240. this._onError(`Neither theme ${theme} nor default ${fallback} loaded.`);
  241. return;
  242. }
  243. console.warn(`Could not load theme ${theme}, using default ${fallback}.`);
  244. this._outstanding = this._loadTheme(fallback);
  245. return;
  246. }
  247. // If the theme does not yet exist, attempt to wait for it.
  248. this._pending = window.setTimeout(() => {
  249. this._loadSettings();
  250. }, REQUEST_INTERVAL);
  251. }
  252. /**
  253. * Load the theme.
  254. *
  255. * #### Notes
  256. * This method assumes that the `theme` exists.
  257. */
  258. private _loadTheme(theme: string): Promise<void> {
  259. const current = this._current;
  260. const links = this._links;
  261. const themes = this._themes;
  262. const splash = this._splash
  263. ? this._splash.show(themes[theme].isLight)
  264. : new DisposableDelegate(() => undefined);
  265. // Unload any CSS files that have been loaded.
  266. links.forEach(link => {
  267. if (link.parentElement) {
  268. link.parentElement.removeChild(link);
  269. }
  270. });
  271. links.length = 0;
  272. // Unload the previously loaded theme.
  273. const old = current ? themes[current].unload() : Promise.resolve();
  274. return Promise.all([old, themes[theme].load()])
  275. .then(() => {
  276. this._current = theme;
  277. this._themeChanged.emit({
  278. name: 'theme',
  279. oldValue: current,
  280. newValue: theme
  281. });
  282. // Need to force a redraw of the app here to avoid a Chrome rendering
  283. // bug that can leave the scrollbars in an invalid state
  284. this._host.hide();
  285. // If we hide/show the widget too quickly, no redraw will happen.
  286. // requestAnimationFrame delays until after the next frame render.
  287. requestAnimationFrame(() => {
  288. this._host.show();
  289. Private.fitAll(this._host);
  290. splash.dispose();
  291. });
  292. })
  293. .catch(reason => {
  294. this._onError(reason);
  295. splash.dispose();
  296. });
  297. }
  298. /**
  299. * Handle a theme error.
  300. */
  301. private _onError(reason: any): void {
  302. void showDialog({
  303. title: 'Error Loading Theme',
  304. body: String(reason),
  305. buttons: [Dialog.okButton({ label: 'OK' })]
  306. });
  307. }
  308. private _base: string;
  309. private _current: string | null = null;
  310. private _host: Widget;
  311. private _links: HTMLLinkElement[] = [];
  312. private _overrides: Dict<string> = {};
  313. private _outstanding: Promise<void> | null = null;
  314. private _pending = 0;
  315. private _requests: { [theme: string]: number } = {};
  316. private _settings: ISettingRegistry.ISettings;
  317. private _splash: ISplashScreen | null;
  318. private _themes: { [key: string]: IThemeManager.ITheme } = {};
  319. private _themeChanged = new Signal<this, IChangedArgs<string>>(this);
  320. }
  321. export namespace ThemeManager {
  322. /**
  323. * The options used to create a theme manager.
  324. */
  325. export interface IOptions {
  326. /**
  327. * The host widget for the theme manager.
  328. */
  329. host: Widget;
  330. /**
  331. * The setting registry key that holds theme setting data.
  332. */
  333. key: string;
  334. /**
  335. * The settings registry.
  336. */
  337. settings: ISettingRegistry;
  338. /**
  339. * The splash screen to show when loading themes.
  340. */
  341. splash?: ISplashScreen;
  342. /**
  343. * The url for local theme loading.
  344. */
  345. url: string;
  346. }
  347. /**
  348. * Some basic CSS properties, corresponding to the naming
  349. * conventions of theme CSS variables
  350. */
  351. const cssProps = ['color', 'font-family', 'size'];
  352. /**
  353. * Validate a CSS value w.r.t. a key
  354. *
  355. * @param key - A Jupyterlab CSS variable, without the leading '--jp-'.
  356. *
  357. * @param val - A candidate CSS value
  358. */
  359. export const validateCSS = (key: string, val: string): boolean => {
  360. // determine the css property corresponding to the key
  361. let prop: string;
  362. for (const p of cssProps) {
  363. if (key.includes(p)) {
  364. prop = p;
  365. break;
  366. }
  367. }
  368. if (!prop) {
  369. console.warn(
  370. 'CSS validation failed: could not find property corresponding to key.\n' +
  371. `key: '${key}', val: '${val}'`
  372. );
  373. return false;
  374. }
  375. // use built-in validation once we have the corresponding property
  376. if (CSS.supports(prop, val)) {
  377. return true;
  378. } else {
  379. console.warn(
  380. 'CSS validation failed: invalid value.\n' +
  381. `key: '${key}', val: '${val}', prop: '${prop}'`
  382. );
  383. return false;
  384. }
  385. };
  386. }
  387. /**
  388. * A namespace for module private data.
  389. */
  390. namespace Private {
  391. /**
  392. * Fit a widget and all of its children, recursively.
  393. */
  394. export function fitAll(widget: Widget): void {
  395. each(widget.children(), fitAll);
  396. widget.fit();
  397. }
  398. }