Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions src/components/controls.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React from 'react';
import { css } from '@emotion/core';
import DarkModeController from '../util/DarkModeController';

const controlsStyles = {
header: css/* scss */ `
position: fixed;
padding: 0.25ch 1ch;
margin-bottom: 1ch;
margin-top: -1ch;
right: 0;
z-index: 999;
box-sizing: border-box;
will-change: transform;

display: grid;
grid-auto-flow: column dense;
grid-gap: 1ch;
align-items: center;

opacity: 0.9;
color: var(--color-text-accent, #999);
background-color: var(--black9, #9993);
border-top-left-radius: 1ch;
border-bottom-left-radius: 1ch;

min-width: max-content;
width: 0;
white-space: normal;
text-size-adjust: 100%;
text-shadow: #333f46 0px 0.875px 0px;
user-select: none;
`,
button: css/* scss */ `
color: inherit;
border: none;
width: max-content;
display: contents;
`,
controls: css/* scss */ `
color: inherit;
`,
};

interface Props {
lightModeIcon?: string;
darkModeIcon?: string;
controller?: DarkModeController;
}

const Controls = ({
lightModeIcon = 'wb_sunny',
darkModeIcon = 'nights_stay',
controller = new DarkModeController(),
}: Props) => (
<header css={controlsStyles.header}>
<div id="controls" css={controlsStyles.controls}>
<span>
<button
type="button"
css={controlsStyles.button}
id="contrast"
title="Dark/Light"
onPointerDown={(): void => {
controller.onPointerDown();
}}
onPointerUp={(): void => {
controller.onPointerUp();
}}
>
<span className="sr-only">Toggle Dark Mode</span>
<i className="material-icons light-mode-only">{darkModeIcon}</i>
<i className="material-icons dark-mode-only">{lightModeIcon}</i>
</button>
</span>
</div>
</header>
);

export default Controls;
18 changes: 16 additions & 2 deletions src/components/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ import { Link } from 'gatsby';
import React from 'react';
import logoLight from '../images/logos/nodejs-logo-light-mode.svg';
import logoDark from '../images/logos/nodejs-logo-dark-mode.svg';
import DarkModeController from '../util/DarkModeController';

const activeStyleTab = {
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-accent)',
borderBottom: 'var(--space-04) inset var(--color-text-accent)',
};

const Header = () => (
interface Props {
darkModeController?: DarkModeController;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you type this as required instead of optional you can safely remove the existence checks below.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alt: Just have the header import the controller. May require structural changes to the controller code to not maintain its own state and instead run off local storage / user preferences. This way, most of those helper methods can exist on the module export as pure functions instead of requiring a new instance to be made each time.

}

const Header = ({ darkModeController }: Props) => (
<nav className="nav">
<div className="logo">
<Link to="/">
Expand Down Expand Up @@ -51,7 +56,16 @@ const Header = () => (
<button
type="button"
className="dark-mode-toggle"
onClick={() => document.body.classList.toggle('dark-mode')}
onClick={() => {
if (!darkModeController)
document.body.classList.toggle('dark-mode');
}}
onPointerDown={(): void => {
if (darkModeController) darkModeController.onPointerDown();
}}
onPointerUp={(): void => {
if (darkModeController) darkModeController.onPointerUp();
}}
>
<span className="sr-only">Toggle Dark Mode</span>
<i className="material-icons light-mode-only">nights_stay</i>
Expand Down
5 changes: 4 additions & 1 deletion src/components/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import '../styles/tokens.css';
import '../styles/layout.css';
import '../styles/mobile.css';
import SEO from './seo';
import DarkModeController from '../util/DarkModeController';

interface Props {
children: React.ReactNode;
title?: string;
description?: string;
img?: string;
href: string;
darkModeController?: DarkModeController;
}

const Layout = ({
Expand All @@ -21,11 +23,12 @@ const Layout = ({
description,
img,
location,
darkModeController = new DarkModeController(),
}: Props): JSX.Element => {
return (
<React.Fragment>
<SEO title={title} description={description} img={img} />
<Header />
<Header darkModeController={darkModeController} />
{children}
</React.Fragment>
);
Expand Down
161 changes: 161 additions & 0 deletions src/util/DarkModeController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// @ts-check
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May I recommend you publish this as its own module? :) I'm sure many other projects would enjoy a lightweight dark mode management util.


/*eslint-disable */

export default class DarkModeController {
static get timeout() {
const value = Symbol.for('dark-mode.toggler.timeout');
Object.defineProperty(this, 'timeout', { value, writable: false });
return value;
}

static get resetting() {
const value = Symbol.for('dark-mode.toggler.resetting');
Object.defineProperty(this, 'resetting', { value, writable: false });
return value;
}

static get prefersLightMode() {
const value =
(typeof matchMedia === 'function' &&
matchMedia('(prefers-color-scheme: light)')) ||
undefined;
Object.defineProperty(this, 'prefersLightMode', { value, writable: false });
return value;
}

static get prefersDarkMode() {
const value =
(typeof matchMedia === 'function' &&
matchMedia('(prefers-color-scheme: dark)')) ||
undefined;
Object.defineProperty(this, 'prefersDarkMode', { value, writable: false });
return value;
}

/** @param {HTMLElement} [target] */
constructor(target) {
Object.defineProperties(this, {
target: {
value:
/** @type {HTMLElement|undefined} */ (target ||
(typeof document === 'object' && document.body) ||
undefined),
writable: false,
},
[DarkModeController.timeout]: {
value: /** @type {number|undefined} */ (undefined),
writable: true,
},
[DarkModeController.resetting]: {
value: /** @type {boolean|undefined} */ (undefined),
writable: true,
},
state: {
value: /** @type {DarkModeState|undefined} */ (undefined),
writable: true,
},
prefers: {
value: /** @type {PrefersColorSchemes|undefined} */ (undefined),
writable: true,
},
enable: { value: this.enable.bind(this), writable: false },
disable: { value: this.disable.bind(this), writable: false },
toggle: { value: this.toggle.bind(this), writable: false },
onPointerDown: { value: this.onPointerDown.bind(this), writable: false },
onPointerUp: { value: this.onPointerUp.bind(this), writable: false },
});

((prefersDarkMode, prefersLightMode, localStorage) => {
if (!localStorage || !prefersDarkMode || !prefersLightMode) return;
localStorage.darkMode === 'enabled'
? ((this.state = 'enabled'), this.enable())
: localStorage.darkMode === 'disabled'
? ((this.state = 'disabled'), this.disable())
: this.toggle(
prefersDarkMode.matches === true ||
prefersLightMode.matches !== true,
!!(localStorage.darkMode = this.state = 'auto')
);
prefersDarkMode.addListener(
({ matches = false }) =>
matches === true && this.toggle(!!matches, true)
);
prefersLightMode.addListener(
({ matches = false }) => matches === true && this.toggle(!matches, true)
);
})(
DarkModeController.prefersDarkMode,
DarkModeController.prefersLightMode,
(typeof localStorage === 'object' && localStorage) || undefined
);

Object.preventExtensions(this);
}

/**
* @param {DarkModeState|boolean} [state]
* @param {boolean} [auto]
*/
async toggle(state, auto) {
const { classList } = this.target;

if (auto === true) {
if (state === true) this.prefers = 'dark';
else if (state === false) this.prefers = 'light';
if (this.state !== 'auto') return;
}

state =
state === 'auto'
? ((auto = true), this.prefers !== 'light')
: state == null
? !classList.contains('dark-mode')
: !!state;

this.state = localStorage.darkMode = auto
? 'auto'
: state
? 'enabled'
: 'disabled';

state
? (classList.add('dark-mode'), classList.remove('light-mode'))
: (classList.add('light-mode'), classList.remove('dark-mode'));
}

/** @param {boolean} [auto] */
enable(auto) {
this.toggle(true, auto);
}

/** @param {boolean} [auto] */
disable(auto) {
this.toggle(false, auto);
}

onPointerDown() {
clearTimeout(this[DarkModeController.timeout]);
this[DarkModeController.timeout] = setTimeout(() => {
this.toggle('auto');
this[DarkModeController.resetting] = true;
// console.log('Reset dark mode!');
}, 2000);
}

onPointerUp() {
this[DarkModeController.timeout] = clearTimeout(
this[DarkModeController.timeout]
);
this[DarkModeController.resetting] === true
? (this[DarkModeController.resetting] = false)
: this.toggle();
}
}

Object.preventExtensions(DarkModeController);

/** @typedef {'auto'|'enabled'|'disabled'} DarkModeState */
/** @typedef {'light'|'dark'} PrefersColorSchemes */

/* eslint-enable */
Loading