Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] [Theme] configure appearance color mode (#203406) #205239

Merged
merged 1 commit into from
Dec 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ import { KibanaRenderContextProvider } from '@kbn/react-kibana-context-render';
import { findTestSubject } from '@kbn/test-jest-helpers';
import { ChromeService } from './chrome_service';

const mockhandleSystemColorModeChange = jest.fn();

jest.mock('./handle_system_colormode_change', () => {
return {
handleSystemColorModeChange: (...args: any[]) => mockhandleSystemColorModeChange(...args),
};
});

class FakeApp implements App {
public title: string;
public mount = () => () => {};
Expand Down Expand Up @@ -205,6 +213,29 @@ describe('start', () => {
expect(startDeps.notifications.toasts.addWarning).not.toBeCalled();
});

it('calls handleSystemColorModeChange() with the correct parameters', async () => {
mockhandleSystemColorModeChange.mockReset();
await start();
expect(mockhandleSystemColorModeChange).toHaveBeenCalledTimes(1);

const [firstCallArg] = mockhandleSystemColorModeChange.mock.calls[0];
expect(Object.keys(firstCallArg).sort()).toEqual([
'coreStart',
'http',
'notifications',
'stop$',
'uiSettings',
]);

expect(mockhandleSystemColorModeChange).toHaveBeenCalledWith({
http: expect.any(Object),
coreStart: expect.any(Object),
uiSettings: expect.any(Object),
notifications: expect.any(Object),
stop$: expect.any(Object),
});
});

describe('getHeaderComponent', () => {
it('returns a renderable React component', async () => {
const { chrome } = await start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import { mergeMap, map, takeUntil, filter } from 'rxjs';
import { parse } from 'url';
import { setEuiDevProviderWarning } from '@elastic/eui';
import useObservable from 'react-use/lib/useObservable';
import type { I18nStart } from '@kbn/core-i18n-browser';
import type { ThemeServiceStart } from '@kbn/core-theme-browser';
import type { UserProfileService } from '@kbn/core-user-profile-browser';
import type { IUiSettingsClient } from '@kbn/core-ui-settings-browser';

import type { CoreContext } from '@kbn/core-base-browser-internal';
import type { InternalInjectedMetadataStart } from '@kbn/core-injected-metadata-browser-internal';
Expand Down Expand Up @@ -54,6 +58,7 @@ import { Header, LoadingIndicator, ProjectHeader } from './ui';
import { registerAnalyticsContextProvider } from './register_analytics_context_provider';
import type { InternalChromeStart } from './types';
import { HeaderTopBanner } from './ui/header/header_top_banner';
import { handleSystemColorModeChange } from './handle_system_colormode_change';

const IS_LOCKED_KEY = 'core.chrome.isLocked';
const IS_SIDENAV_COLLAPSED_KEY = 'core.chrome.isSideNavCollapsed';
Expand All @@ -76,6 +81,10 @@ export interface StartDeps {
injectedMetadata: InternalInjectedMetadataStart;
notifications: NotificationsStart;
customBranding: CustomBrandingStart;
i18n: I18nStart;
theme: ThemeServiceStart;
userProfile: UserProfileService;
uiSettings: IUiSettingsClient;
}

/** @internal */
Expand Down Expand Up @@ -238,9 +247,21 @@ export class ChromeService {
injectedMetadata,
notifications,
customBranding,
i18n: i18nService,
theme,
userProfile,
uiSettings,
}: StartDeps): Promise<InternalChromeStart> {
this.initVisibility(application);
this.handleEuiFullScreenChanges();

handleSystemColorModeChange({
notifications,
coreStart: { i18n: i18nService, theme, userProfile },
stop$: this.stop$,
http,
uiSettings,
});
// commented out until https://github.com/elastic/kibana/issues/201805 can be fixed
// this.handleEuiDevProviderWarning(notifications);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { i18nServiceMock } from '@kbn/core-i18n-browser-mocks';
import { userProfileServiceMock } from '@kbn/core-user-profile-browser-mocks';
import { themeServiceMock } from '@kbn/core-theme-browser-mocks';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
import { uiSettingsServiceMock } from '@kbn/core-ui-settings-browser-mocks';
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
import { handleSystemColorModeChange } from './handle_system_colormode_change';
import { ReplaySubject } from 'rxjs';
import type { GetUserProfileResponse } from '@kbn/core-user-profile-browser';
import { UserProfileData } from '@kbn/core-user-profile-common';
import { IUiSettingsClient } from '@kbn/core-ui-settings-browser';

const mockbrowsersSupportsSystemTheme = jest.fn();

jest.mock('@kbn/core-theme-browser-internal', () => {
const original = jest.requireActual('@kbn/core-theme-browser-internal');

return {
...original,
browsersSupportsSystemTheme: () => mockbrowsersSupportsSystemTheme(),
};
});

describe('handleSystemColorModeChange', () => {
const originalMatchMedia = window.matchMedia;

afterAll(() => {
window.matchMedia = originalMatchMedia;
});

const getDeps = () => {
const coreStart = {
i18n: i18nServiceMock.createStartContract(),
theme: themeServiceMock.createStartContract(),
userProfile: userProfileServiceMock.createStart(),
};
const notifications = notificationServiceMock.createStartContract();
const http = httpServiceMock.createStartContract();
const uiSettings = uiSettingsServiceMock.createStartContract();
const stop$ = new ReplaySubject<void>(1);

return {
coreStart,
notifications,
http,
uiSettings,
stop$,
};
};

const mockMatchMedia = (matches: boolean = false, addEventListenerMock = jest.fn()) => {
const removeEventListenerMock = jest.fn();
window.matchMedia = jest.fn().mockImplementation(() => {
return {
matches,
addEventListener: addEventListenerMock,
removeEventListener: removeEventListenerMock,
};
});

return { addEventListenerMock, removeEventListenerMock };
};

const mockUserProfileResponse = (
darkMode: 'dark' | 'light' | 'system' | 'space_default'
): GetUserProfileResponse<UserProfileData> =>
({
data: {
userSettings: {
darkMode,
},
},
} as any);

const mockUiSettingsDarkMode = (
uiSettings: jest.Mocked<IUiSettingsClient>,
darkMode: 'dark' | 'light' | 'system'
) => {
uiSettings.get.mockImplementation((key) => {
if (key === 'theme:darkMode') {
return darkMode;
}

return 'foo';
});
};

describe('doHandle guard', () => {
it('does not handle if the system color mode is not supported', () => {
const { addEventListenerMock } = mockMatchMedia();
expect(addEventListenerMock).not.toHaveBeenCalled();
mockbrowsersSupportsSystemTheme.mockReturnValue(false);

handleSystemColorModeChange({} as any);

expect(addEventListenerMock).not.toHaveBeenCalled();
});

it('does not handle on unauthenticated routes', () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const { addEventListenerMock } = mockMatchMedia();
expect(addEventListenerMock).not.toHaveBeenCalled();

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(true);

handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });

expect(addEventListenerMock).not.toHaveBeenCalled();
});

it('does not handle if user profile darkmode is not "system"', () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const { addEventListenerMock } = mockMatchMedia();
expect(addEventListenerMock).not.toHaveBeenCalled();

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue({
data: {
userSettings: {
darkMode: 'light',
},
},
} as any);

handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });

expect(addEventListenerMock).not.toHaveBeenCalled();
});

it('does not handle if user profile darkmode is "space_default" but the uiSettings darkmode is not "system"', () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const { addEventListenerMock } = mockMatchMedia();
expect(addEventListenerMock).not.toHaveBeenCalled();

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue({
data: {
userSettings: {
darkMode: 'space_default',
},
},
} as any);

uiSettings.get.mockImplementation((key) => {
if (key === 'theme:darkMode') {
return 'light';
}

return 'foo';
});

handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });

expect(addEventListenerMock).not.toHaveBeenCalled();
});

it('does handle if user profile darkmode is "system"', async () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const { addEventListenerMock } = mockMatchMedia(false);
expect(addEventListenerMock).not.toHaveBeenCalled();

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue(mockUserProfileResponse('system'));

await handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });

expect(addEventListenerMock).toHaveBeenCalled();
});

it('does handle if user profile darkmode is "space_default" and uiSetting darkmode is "system"', async () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const { addEventListenerMock } = mockMatchMedia(false);
expect(addEventListenerMock).not.toHaveBeenCalled();

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue(mockUserProfileResponse('space_default'));
mockUiSettingsDarkMode(uiSettings, 'system');

await handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });

expect(addEventListenerMock).toHaveBeenCalled();
});
});

describe('onDarkModeChange()', () => {
it('does show a toast when the system color mode changes', async () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const currentDarkMode = false; // The system is currently in light mode
const addEventListenerMock = jest
.fn()
.mockImplementation((type: string, cb: (evt: MediaQueryListEvent) => any) => {
expect(notifications.toasts.addSuccess).not.toHaveBeenCalled();
expect(type).toBe('change');
cb({ matches: true } as any); // The system changed to dark mode
expect(notifications.toasts.addSuccess).toHaveBeenCalledWith(
expect.objectContaining({
text: expect.any(Function),
title: 'System color mode updated',
}),
{ toastLifeTimeMs: Infinity }
);
});
mockMatchMedia(currentDarkMode, addEventListenerMock);

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue(mockUserProfileResponse('system'));

await handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });
expect(addEventListenerMock).toHaveBeenCalled();
});

it('does **not** show a toast when the system color mode changes to the current darkmode value', async () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const currentDarkMode = true; // The system is currently in dark mode
const addEventListenerMock = jest
.fn()
.mockImplementation((type: string, cb: (evt: MediaQueryListEvent) => any) => {
expect(notifications.toasts.addSuccess).not.toHaveBeenCalled();
expect(type).toBe('change');
cb({ matches: true } as any); // The system changed to dark mode
expect(notifications.toasts.addSuccess).not.toHaveBeenCalled();
});
mockMatchMedia(currentDarkMode, addEventListenerMock);

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue(mockUserProfileResponse('system'));

await handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });
expect(addEventListenerMock).toHaveBeenCalled();
});

it('stops listening to changes on stop$ change', async () => {
const { coreStart, notifications, http, uiSettings, stop$ } = getDeps();
const currentDarkMode = false; // The system is currently in light mode
const { addEventListenerMock, removeEventListenerMock } = mockMatchMedia(currentDarkMode);

mockbrowsersSupportsSystemTheme.mockReturnValue(true);
http.anonymousPaths.isAnonymous.mockReturnValue(false);
coreStart.userProfile.getCurrent.mockResolvedValue(mockUserProfileResponse('system'));

await handleSystemColorModeChange({ coreStart, notifications, http, uiSettings, stop$ });
expect(addEventListenerMock).toHaveBeenCalled();
expect(removeEventListenerMock).not.toHaveBeenCalled();

stop$.next();

expect(removeEventListenerMock).toHaveBeenCalled();
});
});
});
Loading
Loading