Skip to content

Commit 9fdc4f7

Browse files
committed
[optimize] watch UA Color Scheme changing
1 parent bc9f4cc commit 9fdc4f7

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

models/System.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,26 @@ import { persist, restore } from 'mobx-restful';
33

44
import { isServer } from './configuration';
55

6+
type ColorScheme = 'light' | 'dark';
7+
8+
const matchColorScheme = (color: ColorScheme) =>
9+
globalThis.matchMedia?.(`(prefers-color-scheme: ${color})`);
10+
611
export class SystemModel {
712
@persist()
813
@observable
9-
accessor colorScheme: 'light' | 'dark' = globalThis.matchMedia?.(
10-
'(prefers-color-scheme: dark)',
11-
).matches
14+
accessor colorScheme: 'light' | 'dark' = matchColorScheme('dark').matches
1215
? 'dark'
1316
: 'light';
1417

15-
restored = !isServer() && restore(this, 'System');
16-
18+
restored =
19+
!isServer() &&
20+
restore(this, 'System').then(() =>
21+
matchColorScheme('dark').addEventListener(
22+
'change',
23+
({ matches }) => (this.colorScheme = matches ? 'dark' : 'light'),
24+
),
25+
);
1726
disposer = reaction(
1827
() => this.colorScheme,
1928
scheme => (document.documentElement.dataset.bsTheme = scheme),

0 commit comments

Comments
 (0)