From b38a47f4e60f2873ae38cf7fecaa01818bc575d5 Mon Sep 17 00:00:00 2001 From: David Lechner Date: Fri, 15 Jan 2021 10:50:53 -0600 Subject: [PATCH] use os detection for initial dark mode setting --- src/settings/index.ts | 3 +++ src/utils/os.test.ts | 21 ++++++++++++++++++++- src/utils/os.ts | 16 ++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/settings/index.ts b/src/settings/index.ts index 0c9a2406..8fc3f7e0 100644 --- a/src/settings/index.ts +++ b/src/settings/index.ts @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2021 The Pybricks Authors +import { prefersDarkMode } from '../utils/os'; + // Definitions for user settings. export enum SettingId { @@ -14,6 +16,7 @@ export function getDefaultBooleanValue(id: SettingId): boolean { case SettingId.ShowDocs: return window.innerWidth >= 1024; case SettingId.DarkMode: + return prefersDarkMode(); case SettingId.FlashCurrentProgram: return false; // istanbul ignore next: it is a programmer error if we hit this diff --git a/src/utils/os.test.ts b/src/utils/os.test.ts index 665f08d6..9051252f 100644 --- a/src/utils/os.test.ts +++ b/src/utils/os.test.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2021 The Pybricks Authors -import { isMacOS } from './os'; +import { isMacOS, prefersDarkMode } from './os'; describe('isMacOS', () => { test('is true', () => { @@ -13,3 +13,22 @@ describe('isMacOS', () => { expect(isMacOS()).toBeFalsy(); }); }); + +describe('prefersDarkMode', () => { + test('is true', () => { + window.matchMedia = jest.fn().mockReturnValue({ + matches: true, + } as MediaQueryList); + expect(prefersDarkMode()).toBeTruthy(); + }); + test('is false', () => { + // @ts-expect-error 2790 + delete window.matchMedia; + expect(prefersDarkMode()).toBeFalsy(); + + window.matchMedia = jest.fn().mockReturnValue({ + matches: false, + } as MediaQueryList); + expect(prefersDarkMode()).toBeFalsy(); + }); +}); diff --git a/src/utils/os.ts b/src/utils/os.ts index 44a11446..e32d5471 100644 --- a/src/utils/os.ts +++ b/src/utils/os.ts @@ -3,6 +3,22 @@ // Utility functions for dealing with operating systems. +/** + * Tests if we are running on macOS. + * @returns `true` if running on macOS, otherwise `false`. + */ export function isMacOS(): boolean { return /mac/i.test(navigator.platform); } + +/** + * Tests if the OS is set to dark mode. + * @returns: `true` if dark mode should be preferred, otherwise `false`. + */ +export function prefersDarkMode(): boolean { + if (!window.matchMedia) { + return false; + } + + return window.matchMedia('(prefers-color-scheme: dark)').matches; +}