Skip to content

Commit fbba51c

Browse files
committed
feat(ScrollBar): ✨ support dark mode by js
1 parent bf79bff commit fbba51c

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

src/ScrollBar.tsx

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import raf from 'rc-util/lib/raf';
33
import * as React from 'react';
44
import { getPageXY } from './hooks/useScrollDrag';
55

6+
const isDark = () => window.matchMedia?.('(prefers-color-scheme: dark)').matches;
7+
68
export type ScrollBarDirectionType = 'ltr' | 'rtl';
79

810
export interface ScrollBarProps {
@@ -45,6 +47,7 @@ const ScrollBar = React.forwardRef<ScrollBarRef, ScrollBarProps>((props, ref) =>
4547
const [dragging, setDragging] = React.useState(false);
4648
const [pageXY, setPageXY] = React.useState<number | null>(null);
4749
const [startTop, setStartTop] = React.useState<number | null>(null);
50+
const [dark, setDark] = React.useState(isDark());
4851

4952
const isLTR = !rtl;
5053

@@ -187,6 +190,20 @@ const ScrollBar = React.forwardRef<ScrollBarRef, ScrollBarProps>((props, ref) =>
187190
}
188191
}, [dragging]);
189192

193+
React.useEffect(() => {
194+
const media = window.matchMedia?.('(prefers-color-scheme: dark)');
195+
196+
const listener = (e: MediaQueryListEvent) => {
197+
setDark(e.matches);
198+
};
199+
200+
media?.addEventListener('change', listener);
201+
202+
return () => {
203+
media?.removeEventListener('change', listener);
204+
};
205+
}, []);
206+
190207
React.useEffect(() => {
191208
delayHidden();
192209
return () => {
@@ -209,10 +226,11 @@ const ScrollBar = React.forwardRef<ScrollBarRef, ScrollBarProps>((props, ref) =>
209226

210227
const thumbStyle: React.CSSProperties = {
211228
position: 'absolute',
212-
background: 'rgba(0, 0, 0, 0.5)',
229+
background: dark ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)',
213230
borderRadius: 99,
214231
cursor: 'pointer',
215232
userSelect: 'none',
233+
...propsThumbStyle,
216234
};
217235

218236
if (horizontal) {
@@ -266,7 +284,7 @@ const ScrollBar = React.forwardRef<ScrollBarRef, ScrollBarProps>((props, ref) =>
266284
className={classNames(`${scrollbarPrefixCls}-thumb`, {
267285
[`${scrollbarPrefixCls}-thumb-moving`]: dragging,
268286
})}
269-
style={{ ...thumbStyle, ...propsThumbStyle }}
287+
style={{ ...thumbStyle }}
270288
onMouseDown={onThumbMouseDown}
271289
/>
272290
</div>

0 commit comments

Comments
 (0)