Skip to content

Commit

Permalink
feat: Default color mode to user's current system theme (#3456)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajay-sentry authored Oct 31, 2024
1 parent 36e5560 commit b92c538
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@
--color-code-operator: 219 178, 89;
}

/* Also used for prefers-color-scheme: light */
/* explicitly define it below if we want to change behavior */
body {
@apply lightMode;
}
Expand All @@ -261,7 +263,7 @@
@apply darkMode;
}

/* new body theme can be applied here
/* new body theme can be applied here */

@media (prefers-color-scheme: dark) {
body {
Expand All @@ -271,9 +273,7 @@
body.light {
@apply lightMode;
}
new body theme added above should be applied here as well to cover specificity
} */
}
}

#sentry-feedback {
Expand Down
1 change: 1 addition & 0 deletions src/shared/ThemeContext/ThemeContext.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe('Theme context', () => {
function setup() {
window.localStorage.__proto__.setItem = vi.fn()
window.localStorage.__proto__.getItem = vi.fn()
window.matchMedia = vi.fn().mockResolvedValue({ matches: false })

const user = userEvent.setup()

Expand Down
11 changes: 9 additions & 2 deletions src/shared/ThemeContext/ThemeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,15 @@ interface ThemeContextProviderProps {
export const ThemeContextProvider: FC<ThemeContextProviderProps> = ({
children,
}) => {
const currentTheme = (localStorage.getItem('theme') as Theme) || Theme.LIGHT
const [theme, setTheme] = useState<Theme>(currentTheme)
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches

let systemTheme = Theme.LIGHT
if (prefersDark) {
systemTheme = Theme.DARK
}

const currentTheme = localStorage.getItem('theme') as Theme
const [theme, setTheme] = useState<Theme>(currentTheme ?? systemTheme)
const initialRender = useRef(true)

if (initialRender.current) {
Expand Down
2 changes: 2 additions & 0 deletions src/vitest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ vi.mock('@sentry/react', async () => {
}
})

window.matchMedia = vi.fn().mockResolvedValue({ matches: false })

beforeAll(() => {
globalThis.jest = {
...globalThis.jest,
Expand Down

0 comments on commit b92c538

Please sign in to comment.