Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/frontend/account/dark-mode.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { throttle, isEqual } from "lodash";6import { AccountStore } from "./store";78export const dark_mode_mins = {9brightness: 20,10contrast: 20,11sepia: 0,12grayscale: 0,13} as const;1415interface Config {16brightness: number;17contrast: number;18sepia: number;19grayscale: number;20}2122// Returns number between 0 and 100.23function to_number(x: any, default_value: number): number {24if (x == null) return default_value;25try {26x = parseInt(x);27if (isNaN(x)) {28return default_value;29}30if (x < 0) {31x = 0;32}33if (x > 100) {34x = 100;35}36return x;37} catch (_) {38return default_value;39}40}4142export function get_dark_mode_config(other_settings?: {43dark_mode_brightness?: number;44dark_mode_contrast?: number;45dark_mode_sepia?: number;46dark_mode_grayscale?: number;47}): Config {48const brightness = Math.max(49dark_mode_mins.brightness,50to_number(other_settings?.dark_mode_brightness, 100),51);52const contrast = Math.max(53dark_mode_mins.contrast,54to_number(other_settings?.dark_mode_contrast, 90),55);56const sepia = to_number(57other_settings?.dark_mode_sepia,58dark_mode_mins.sepia,59);60const grayscale = to_number(61other_settings?.dark_mode_grayscale,62dark_mode_mins.grayscale,63);64return { brightness, contrast, sepia, grayscale };65}6667let currentDarkMode: boolean = false;68let last_dark_mode: boolean = false;69let last_config: Config | undefined = undefined;70export function init_dark_mode(account_store: AccountStore): void {71account_store.on(72"change",73throttle(async () => {74const dark_mode = !!account_store.getIn(["other_settings", "dark_mode"]);75currentDarkMode = dark_mode;76const config = get_dark_mode_config(77account_store.get("other_settings")?.toJS(),78);79if (80dark_mode == last_dark_mode &&81(!dark_mode || isEqual(last_config, config))82) {83return;84}85const { enable, disable } = await import("darkreader");86last_dark_mode = dark_mode;87last_config = config;88if (dark_mode) {89enable(config);90} else {91disable();92}93}, 3000),94);95}9697export function inDarkMode() {98return currentDarkMode;99}100101102