Skip to content

Commit 813663d

Browse files
committed
make button tri-state + take up less space
1 parent 35e07c7 commit 813663d

6 files changed

Lines changed: 84 additions & 65 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# jamstacks
22

3-
Shared React components for Jamstacks templates. The initial library provides a dark-mode switch and a shared theme API. It works with React 18.2+ and React 19, including Next.js App Router and static exports, with no Next.js or Tailwind runtime dependency.
3+
Shared React components for Jamstacks templates. The initial library provides a light/dark/system theme toggle and a shared theme API. It works with React 18.2+ and React 19, including Next.js App Router and static exports, with no Next.js or Tailwind runtime dependency.
44

55
## Install in a template
66

@@ -44,7 +44,7 @@ export default function App() {
4444
}
4545
```
4646

47-
Use one provider per document and place all switches inside it. Multiple switches share the same state. `DarkModeToggle` is a native keyboard-accessible button with `role="switch"`, a default accessible name of "Dark mode", and a live `aria-checked` value. It supports a forwarded button ref and ordinary button props, including `className`, `style`, `disabled`, `aria-label`, and `onClick`. Calling `event.preventDefault()` in `onClick` cancels the theme change. It stays disabled until hydration finishes so a click cannot overwrite a saved preference before it has loaded.
47+
Use one provider per document and place all toggles inside it. Multiple toggles share the same state. `DarkModeToggle` is a single native keyboard-accessible button that cycles between three preferences, showing a sun, moon or monitor icon for the current one. From System, a click switches to the opposite of the device's appearance, then to the device's appearance, then back to System, so the first click always changes what the visitor sees. Its accessible name and tooltip include the current preference ("Theme: System" by default; `aria-label` replaces the "Theme" prefix), and `data-theme-preference="light|dark|system"` exposes it to template selectors. It supports a forwarded button ref and ordinary button props, including `className`, `style`, `disabled`, `aria-label`, and `onClick`. Calling `event.preventDefault()` in `onClick` cancels the theme change. It stays disabled until hydration finishes so a click cannot overwrite a saved preference before it has loaded.
4848

4949
## Next.js App Router
5050

@@ -72,7 +72,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
7272
import { DarkModeToggle } from 'jamstacks';
7373

7474
export default function Header() {
75-
return <header><DarkModeToggle aria-label="Dark mode" /></header>;
75+
return <header><DarkModeToggle aria-label="Theme" /></header>;
7676
}
7777
```
7878

@@ -108,7 +108,7 @@ An existing template that uses only `@media (prefers-color-scheme: dark)` needs
108108
body { background: var(--page-background); color: var(--page-ink); }
109109
```
110110

111-
Apply the same pattern to all of the template's dark palette variables, including inherited `--jamstacks-*` component fallbacks. With Tailwind, configure its dark variant to use the `.dark` class rather than a media query. The toggle carries its own inline styles and needs no stylesheet import or global CSS rules. Its colours can be customized through `--jamstacks-toggle-background`, `--jamstacks-toggle-dark-background`, `--jamstacks-toggle-border`, `--jamstacks-toggle-color`, `--jamstacks-toggle-dark-color`, and `--jamstacks-toggle-thumb`. The `style` prop overrides the button's defaults; `className` remains available for template selectors. It preserves the browser's native keyboard-focus outline. Theme changes are instantaneous, with no animation that needs reduced-motion handling.
111+
Apply the same pattern to all of the template's dark palette variables, including inherited `--jamstacks-*` component fallbacks. With Tailwind, configure its dark variant to use the `.dark` class rather than a media query. The toggle carries its own inline styles and needs no stylesheet import or global CSS rules. Its colours can be customized through `--jamstacks-toggle-background`, `--jamstacks-toggle-dark-background`, `--jamstacks-toggle-border`, `--jamstacks-toggle-color`, and `--jamstacks-toggle-dark-color`. The `style` prop overrides the button's defaults; `className` remains available for template selectors. It preserves the browser's native keyboard-focus outline. Theme changes are instantaneous, with no animation that needs reduced-motion handling.
112112

113113
## Theme API
114114

‎demo/main.tsx‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ const accentTokens = {
88
'--jamstacks-toggle-background': '#e9ddff',
99
'--jamstacks-toggle-dark-background': '#7152a3',
1010
'--jamstacks-toggle-color': '#51347a',
11-
'--jamstacks-toggle-thumb': '#fdfaff',
1211
} as CSSProperties;
1312

1413
function Playground() {
@@ -34,17 +33,17 @@ function Playground() {
3433
<main>
3534
<div className="demo-intro">
3635
<p className="demo-eyebrow">React component library</p>
37-
<h1>A little switch.<br />A shared preference.</h1>
38-
<p>Try the dark-mode toggle, inspect the current theme, and see every instance stay in sync.</p>
36+
<h1>A little toggle.<br />A shared preference.</h1>
37+
<p>Try the theme toggle, inspect the current theme, and see every instance stay in sync.</p>
3938
</div>
4039

4140
<div className="demo-grid">
4241
<section className="demo-card" aria-labelledby="appearance-heading">
4342
<p className="demo-eyebrow">01 / Appearance</p>
4443
<h2 id="appearance-heading">Choose your theme</h2>
4544
<div className="demo-switch-row">
46-
<div><strong>Dark mode</strong><p>The switch makes an explicit light or dark choice.</p></div>
47-
<DarkModeToggle ref={toggle} aria-label="Main dark mode switch" />
45+
<div><strong>Theme</strong><p>One button cycles System, the opposite of your device, then your device’s mode.</p></div>
46+
<DarkModeToggle ref={toggle} aria-label="Main theme" />
4847
</div>
4948
<div className="demo-preferences" role="group" aria-label="Theme preference">
5049
{(['light', 'dark', 'system'] as Theme[]).map(value => (
@@ -89,12 +88,12 @@ function Playground() {
8988
<li>Choose a mode and reload. Your choice should remain.</li>
9089
<li>Open a second tab. Switching in either tab should update the other.</li>
9190
<li>Choose System, then change the device’s appearance.</li>
92-
<li>Use Tab to focus a switch, then Space or Enter to activate it.</li>
91+
<li>Use Tab to focus a toggle, then Space or Enter to activate it.</li>
9392
</ol>
9493
</div>
9594
<div className="demo-actions">
9695
<a className="demo-button" href="/" target="_blank" rel="noreferrer">Open another tab <span aria-hidden="true">↗</span></a>
97-
<button className="demo-button demo-button-secondary" type="button" onClick={() => toggle.current?.focus()}>Focus main switch</button>
96+
<button className="demo-button demo-button-secondary" type="button" onClick={() => toggle.current?.focus()}>Focus main toggle</button>
9897
</div>
9998
</section>
10099
</main>

‎src/components/DarkModeToggle.tsx‎

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,49 @@
33
import { forwardRef } from 'react';
44
import type { ButtonHTMLAttributes, CSSProperties } from 'react';
55
import { useTheme } from '../theme/ThemeProvider.js';
6+
import type { ResolvedTheme, Theme } from '../theme/types.js';
67

7-
export interface DarkModeToggleProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'role' | 'aria-checked'> {}
8+
export interface DarkModeToggleProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'role' | 'aria-checked' | 'aria-pressed'> {}
9+
10+
const names: Record<Theme, string> = { light: 'Light', dark: 'Dark', system: 'System' };
811

912
const buttonStyle: CSSProperties = {
10-
display: 'inline-flex',
11-
alignItems: 'center',
13+
display: 'inline-grid',
14+
placeItems: 'center',
1215
flexShrink: 0,
1316
boxSizing: 'border-box',
14-
width: '2.875rem',
15-
height: '1.625rem',
16-
padding: 2,
17+
width: '2rem',
18+
height: '2rem',
19+
padding: 0,
1720
border: '1px solid var(--jamstacks-toggle-border, #788579)',
1821
borderRadius: 999,
1922
outlineOffset: 3,
2023
};
2124

22-
const thumbStyle: CSSProperties = {
23-
display: 'grid',
24-
placeItems: 'center',
25-
width: '1.25rem',
26-
height: '1.25rem',
27-
borderRadius: '50%',
28-
background: 'var(--jamstacks-toggle-thumb, #ffffff)',
29-
color: 'var(--jamstacks-toggle-color, #243c2d)',
30-
boxShadow: '0 1px 3px #0003',
31-
};
25+
const iconStyle: CSSProperties = { display: 'block', width: '1rem', height: '1rem' };
26+
27+
function deviceTheme(): ResolvedTheme {
28+
try { return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } catch { return 'light'; }
29+
}
30+
31+
/**
32+
* Cycles through the three preferences so that the first click always changes the appearance:
33+
* system → opposite of the device → same as the device → system.
34+
*/
35+
function nextTheme(theme: Theme, device: ResolvedTheme): Theme {
36+
const opposite: ResolvedTheme = device === 'dark' ? 'light' : 'dark';
37+
if (theme === 'system') return opposite;
38+
return theme === opposite ? device : 'system';
39+
}
3240

33-
/** A labelled switch with encapsulated inline styles; no stylesheet import is needed. */
41+
/** A single tri-state light / dark / system button with encapsulated inline styles; no stylesheet import is needed. */
3442
export const DarkModeToggle = forwardRef<HTMLButtonElement, DarkModeToggleProps>(function DarkModeToggle(
35-
{ className, style, onClick, disabled, 'aria-label': label = 'Dark mode', ...props }, ref,
43+
{ className, style, onClick, disabled, title, 'aria-label': label = 'Theme', ...props }, ref,
3644
) {
37-
const { resolvedTheme, setTheme, mounted } = useTheme();
45+
const { theme, resolvedTheme, setTheme, mounted } = useTheme();
3846
const isDark = resolvedTheme === 'dark';
3947
const isDisabled = disabled || !mounted;
48+
const name = `${label}: ${names[theme]}`;
4049
return (
4150
<button
4251
{...props}
@@ -51,27 +60,26 @@ export const DarkModeToggle = forwardRef<HTMLButtonElement, DarkModeToggleProps>
5160
opacity: isDisabled ? .55 : 1,
5261
...style,
5362
}}
54-
role="switch"
55-
aria-label={label}
56-
aria-checked={isDark}
63+
aria-label={name}
64+
title={title ?? name}
65+
data-theme-preference={theme}
5766
disabled={isDisabled}
5867
onClick={event => {
5968
onClick?.(event);
60-
if (!event.defaultPrevented) setTheme(isDark ? 'light' : 'dark');
69+
if (!event.defaultPrevented) setTheme(nextTheme(theme, theme === 'system' ? resolvedTheme : deviceTheme()));
6170
}}
6271
>
63-
<span
64-
className="jamstacks-dark-mode-toggle__thumb"
65-
style={{ ...thumbStyle, transform: isDark ? 'translateX(1.25rem)' : 'translateX(0)' }}
66-
aria-hidden="true"
67-
>
68-
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" focusable="false">
69-
{isDark ? <path d="M20.5 13A8.5 8.5 0 0 1 11 3.5 8.5 8.5 0 1 0 20.5 13Z" /> : <>
72+
<svg className="jamstacks-dark-mode-toggle__icon" style={iconStyle} viewBox="0 0 24 24" fill="none" stroke="currentColor"
73+
strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
74+
{theme === 'dark' ? <path d="M20.5 13A8.5 8.5 0 0 1 11 3.5 8.5 8.5 0 1 0 20.5 13Z" />
75+
: theme === 'light' ? <>
7076
<circle cx="12" cy="12" r="4" />
7177
<path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5" />
78+
</> : <>
79+
<rect x="3" y="4" width="18" height="12" rx="2" />
80+
<path d="M8 20h8m-4-4v4" />
7281
</>}
73-
</svg>
74-
</span>
82+
</svg>
7583
</button>
7684
);
7785
});

‎tests/fixture.mjs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ function Controls() {
77
return h('main', null,
88
h('h1', null, 'Jamstacks theme fixture'),
99
h(DarkModeToggle, { 'data-testid': 'toggle' }),
10-
h(DarkModeToggle, { 'aria-label': 'Second dark mode switch' }),
11-
h(DarkModeToggle, { 'aria-label': 'Custom styled switch', style: { width: 64, background: 'rgb(128, 0, 128)' } }),
12-
h(DarkModeToggle, { disabled: true, 'aria-label': 'Disabled switch' }),
13-
h(DarkModeToggle, { onClick: e => e.preventDefault(), 'aria-label': 'Cancelled switch' }),
10+
h(DarkModeToggle, { 'aria-label': 'Second toggle' }),
11+
h(DarkModeToggle, { 'aria-label': 'Custom toggle', style: { width: 64, background: 'rgb(128, 0, 128)' } }),
12+
h(DarkModeToggle, { disabled: true, 'aria-label': 'Disabled toggle' }),
13+
h(DarkModeToggle, { onClick: e => e.preventDefault(), 'aria-label': 'Cancelled toggle' }),
1414
h('button', { onClick: () => setTheme('system') }, 'Use system'),
1515
h('output', { 'data-testid': 'state' }, `${theme}:${resolvedTheme}:${mounted}`),
1616
);

‎tests/package.test.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ import { ThemeScript, getThemeScript } from 'jamstacks/server';
88

99
test('public exports render on the server without browser globals', () => {
1010
const html = renderToString(createElement(ThemeProvider, null, createElement(DarkModeToggle)));
11-
assert.match(html, /role="switch"/);
12-
assert.match(html, /aria-label="Dark mode"/);
13-
assert.match(html, /aria-checked="false"/);
11+
assert.doesNotMatch(html, /role=/);
12+
assert.match(html, /aria-label="Theme: System"/);
13+
assert.match(html, /data-theme-preference="system"/);
1414
assert.match(html, /disabled=""/);
1515
assert.match(renderToString(createElement(ThemeScript, { nonce: 'example-nonce' })), /nonce="example-nonce"/);
1616
});

‎tests/theme.spec.mjs‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,52 @@ async function ready(page, path = '/') {
55
await expect(page.getByTestId('state')).toContainText(':true');
66
}
77

8-
test('system preference, explicit overrides, persistence and shared switches', async ({ page }) => {
8+
const pref = 'data-theme-preference';
9+
10+
test('cycles system, opposite of device, device, then system with persistence and shared toggles', async ({ page }) => {
911
await page.emulateMedia({ colorScheme: 'dark' });
1012
await ready(page);
1113
const toggle = page.getByTestId('toggle');
12-
await expect(toggle).toHaveAttribute('aria-checked', 'true');
14+
await expect(toggle).toHaveAttribute(pref, 'system');
15+
await expect(toggle).toHaveAccessibleName('Theme: System');
16+
await expect(toggle).not.toHaveAttribute('role');
1317
await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
1418
await page.emulateMedia({ colorScheme: 'light' });
15-
await expect(toggle).toHaveAttribute('aria-checked', 'false');
19+
await expect(page.locator('html')).toHaveAttribute('data-theme', 'light');
1620
await toggle.click();
17-
await expect(page.getByRole('switch', { name: 'Second dark mode switch', exact: true })).toHaveAttribute('aria-checked', 'true');
21+
await expect(toggle).toHaveAccessibleName('Theme: Dark');
22+
await expect(page.getByRole('button', { name: 'Second toggle: Dark', exact: true })).toHaveAttribute(pref, 'dark');
1823
expect(await page.evaluate(() => localStorage.getItem('color-scheme'))).toBe('dark');
1924
await page.reload();
20-
await expect(toggle).toHaveAttribute('aria-checked', 'true');
21-
await page.emulateMedia({ colorScheme: 'dark' });
25+
await expect(toggle).toHaveAttribute(pref, 'dark');
2226
await toggle.click();
27+
await expect(toggle).toHaveAttribute(pref, 'light');
2328
await expect(page.locator('html')).toHaveClass('light');
2429
await expect(page.locator('body')).toHaveCSS('background-color', 'rgb(255, 255, 255)');
25-
await page.getByRole('button', { name: 'Use system' }).click();
30+
await toggle.click();
31+
await expect(page.getByTestId('state')).toHaveText('system:light:true');
32+
await page.emulateMedia({ colorScheme: 'dark' });
2633
await expect(page.getByTestId('state')).toHaveText('system:dark:true');
34+
await toggle.click();
35+
await expect(page.getByTestId('state')).toHaveText('light:light:true');
2736
});
2837

2938
test('keyboard operation, disabled controls and preventDefault', async ({ page }) => {
39+
await page.emulateMedia({ colorScheme: 'light' });
3040
await ready(page);
3141
const toggle = page.getByTestId('toggle');
3242
await page.keyboard.press('Tab');
3343
await expect(toggle).toBeFocused();
3444
expect(await toggle.evaluate(button => getComputedStyle(button).outlineStyle)).not.toBe('none');
3545
await page.keyboard.press('Space');
36-
await expect(toggle).toHaveAttribute('aria-checked', 'true');
46+
await expect(toggle).toHaveAttribute(pref, 'dark');
47+
await page.keyboard.press('Enter');
48+
await expect(toggle).toHaveAttribute(pref, 'light');
3749
await page.keyboard.press('Enter');
38-
await expect(toggle).toHaveAttribute('aria-checked', 'false');
39-
await expect(page.getByRole('switch', { name: 'Disabled switch', exact: true })).toBeDisabled();
40-
await page.getByRole('switch', { name: 'Cancelled switch', exact: true }).click();
41-
await expect(toggle).toHaveAttribute('aria-checked', 'false');
50+
await expect(toggle).toHaveAttribute(pref, 'system');
51+
await expect(page.getByRole('button', { name: 'Disabled toggle: System', exact: true })).toBeDisabled();
52+
await page.getByRole('button', { name: 'Cancelled toggle: System', exact: true }).click();
53+
await expect(toggle).toHaveAttribute(pref, 'system');
4254
});
4355

4456
test('storage synchronizes across tabs and resets to system when cleared', async ({ context, page }) => {
@@ -85,7 +97,7 @@ test('custom storage keys and defaults, invalid saved values and reduced motion'
8597
await page.emulateMedia({ colorScheme: 'light', reducedMotion: 'reduce' });
8698
await ready(page, '/?custom');
8799
await expect(page.getByTestId('state')).toHaveText('dark:dark:true');
88-
await expect(page.locator('.jamstacks-dark-mode-toggle__thumb').first()).toHaveCSS('transition-duration', '0s');
100+
await expect(page.locator('.jamstacks-dark-mode-toggle__icon').first()).toHaveCSS('transition-duration', '0s');
89101
await page.getByTestId('toggle').click();
90102
expect(await page.evaluate(() => localStorage.getItem('custom-theme'))).toBe('light');
91103
expect(await page.evaluate(() => localStorage.getItem('color-scheme'))).toBeNull();
@@ -97,10 +109,10 @@ test('component styling needs no stylesheet and accepts template customizations'
97109
const toggle = page.getByTestId('toggle');
98110
await page.evaluate(() => document.documentElement.style.setProperty('--jamstacks-toggle-background', 'rgb(255, 0, 0)'));
99111
await expect(toggle).toHaveCSS('background-color', 'rgb(255, 0, 0)');
100-
const custom = page.getByRole('switch', { name: 'Custom styled switch', exact: true });
112+
const custom = page.getByRole('button', { name: /^Custom toggle: / });
101113
await expect(custom).toHaveCSS('background-color', 'rgb(128, 0, 128)');
102114
await custom.click();
103115
await expect(custom).toHaveCSS('background-color', 'rgb(128, 0, 128)');
104-
await expect(toggle).toHaveAttribute('aria-checked', 'true');
116+
await expect(toggle).toHaveAttribute(pref, 'dark');
105117
expect(await page.locator('link[rel="stylesheet"]').count()).toBe(0);
106118
});

0 commit comments

Comments
 (0)