Skip to content

Commit

Permalink
feat: use theme based on user theme preference
Browse files Browse the repository at this point in the history
  • Loading branch information
jonyw4 committed Nov 30, 2021
1 parent 35f24eb commit 2475e67
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
7 changes: 6 additions & 1 deletion webapp/src/infra/ThemeLocalStorageRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ export class ThemeLocalStorageRepository implements ThemeRepository {
const theme = global.localStorage.getItem(LOCAL_STORAGE_THEME_KEY) as Theme;

if(!theme){
return DEFAULT_THEME;
return this.userThemePreference();
}

return theme;
}
private userThemePreference(): Theme {
const darkThemeMq = global.matchMedia("(prefers-color-scheme: dark)");
const isDarkMode = darkThemeMq.matches;
return isDarkMode ? "dark" : "light";
}
changeTheme(theme: Theme): void {
global.localStorage.setItem(LOCAL_STORAGE_THEME_KEY, theme);
}
Expand Down
28 changes: 25 additions & 3 deletions webapp/tests/unit/infra/ThemeLocalStorageRepository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ interface Storage {

describe("infra :: ThemeLocalStorageRepository", () => {

const fakeMatchMedia = jest.fn();
beforeEach(() => {
// @ts-ignore
global.localStorage = createMock<Storage>();
global.matchMedia = fakeMatchMedia;
})

const themeRepository = new ThemeLocalStorageRepository();
Expand All @@ -27,9 +29,29 @@ describe("infra :: ThemeLocalStorageRepository", () => {
});

describe('given an empty localstorage', () => {
it("should get the light theme", () => {
const theme = themeRepository.getTheme();
expect(theme).toBe("light");

describe('with user theme preference as dark', () => {
beforeEach(() => {
fakeMatchMedia.mockReturnValue({
matches: true,
});
})
it("should get the dark theme", () => {
const theme = themeRepository.getTheme();
expect(theme).toBe("dark");
});
})
describe("with user theme preference as light", () => {
beforeEach(() => {
// @ts-ignore
fakeMatchMedia.mockReturnValue({
matches: false,
});
});
it("should get the light theme", () => {
const theme = themeRepository.getTheme();
expect(theme).toBe("light");
});
});
});

Expand Down

1 comment on commit 2475e67

@vercel
Copy link

@vercel vercel bot commented on 2475e67 Nov 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.