1
1
import { useRouter } from 'next/router' ;
2
2
import dynamic from 'next/dynamic' ;
3
- import { Fragment , type PropsWithChildren , useEffect , useState } from 'react' ;
3
+ import {
4
+ Fragment ,
5
+ type PropsWithChildren ,
6
+ useCallback ,
7
+ useEffect ,
8
+ useState
9
+ } from 'react' ;
4
10
import hljs from 'highlight.js' ;
5
11
import Link from 'next/link' ;
6
12
import {
7
13
DBBrand ,
8
- DBButton ,
14
+ DBSwitch ,
15
+ DBTooltip ,
9
16
DBHeader ,
10
17
DBPage ,
11
18
DBSection ,
@@ -20,6 +27,9 @@ import {
20
27
import Navigation from './navigation' ;
21
28
import VersionSwitcher from './version-switcher' ;
22
29
30
+ const preferDark = '(prefers-color-scheme: dark)' ;
31
+ const colorModeKey = 'db-ux-mode' ;
32
+
23
33
const DefaultPage = ( {
24
34
children,
25
35
noNavigation
@@ -38,6 +48,25 @@ const DefaultPage = ({
38
48
const [ breadcrumb , setBreadcrumb ] = useState < NavigationItem [ ] > ( ) ;
39
49
const router = useRouter ( ) ;
40
50
51
+ const [ mode , setMode ] = useState < boolean > (
52
+ localStorage . getItem ( colorModeKey ) === null
53
+ ? globalThis . matchMedia ?.( preferDark ) . matches
54
+ : localStorage . getItem ( colorModeKey ) === 'dark'
55
+ ) ;
56
+
57
+ const setColorMode = useCallback ( ( dark : boolean ) => {
58
+ localStorage . setItem ( colorModeKey , dark ? 'dark' : 'light' ) ;
59
+ setMode ( dark ) ;
60
+ } , [ ] ) ;
61
+
62
+ useEffect ( ( ) => {
63
+ globalThis
64
+ . matchMedia ( preferDark )
65
+ . addEventListener ( 'change' , ( event ) => {
66
+ setColorMode ( event . matches ) ;
67
+ } ) ;
68
+ } , [ ] ) ;
69
+
41
70
useEffect ( ( ) => {
42
71
hljs . configure ( {
43
72
languages : [
@@ -106,6 +135,7 @@ const DefaultPage = ({
106
135
) }
107
136
{ router . isReady && ! fullscreen && (
108
137
< DBPage
138
+ data-mode = { mode ? 'dark' : 'light' }
109
139
fadeIn
110
140
variant = "fixed"
111
141
header = {
@@ -118,12 +148,20 @@ const DefaultPage = ({
118
148
</ DBBrand >
119
149
}
120
150
primaryAction = {
121
- < DBButton
122
- icon = "magnifying_glass"
123
- variant = "ghost"
124
- noText >
125
- Search
126
- </ DBButton >
151
+ < DBSwitch
152
+ checked = { mode }
153
+ visualAid
154
+ icon = "sun"
155
+ iconAfter = "moon"
156
+ showLabel = { false }
157
+ onChange = { ( ) => {
158
+ setColorMode ( ! mode ) ;
159
+ } } >
160
+ < DBTooltip >
161
+ Switch color scheme (light/dark)
162
+ </ DBTooltip >
163
+ Switch color scheme (light/dark)
164
+ </ DBSwitch >
127
165
}
128
166
secondaryAction = { < VersionSwitcher /> } >
129
167
< Navigation />
0 commit comments