Skip to content

Support themes #200

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

Merged
merged 6 commits into from
Jul 28, 2025
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
43 changes: 43 additions & 0 deletions src/common/auth/getRedirectSuffix.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, it, expect, afterAll } from 'vitest';
import { getRedirectSuffix } from './getRedirectSuffix';

const originalLocation = globalThis.location;

function mockLocation(search: string, hash: string) {
Object.defineProperty(globalThis, 'location', {
value: { ...originalLocation, search, hash },
writable: true,
configurable: true,
});
}

// Restore the real object once all tests have finished
afterAll(() => {
Object.defineProperty(globalThis, 'location', {
value: originalLocation,
writable: true,
configurable: true,
});
});

describe('getRedirectSuffix()', () => {
it('returns "/{search}{hash}" when both parts are present', () => {
mockLocation('?sap-theme=sap_horizon', '#/mcp/projects');
expect(getRedirectSuffix()).toBe('/?sap-theme=sap_horizon#/mcp/projects');
});

it('returns "/{search}" when only the query string exists', () => {
mockLocation('?query=foo', '');
expect(getRedirectSuffix()).toBe('/?query=foo');
});

it('returns "{hash}" when only the hash fragment exists', () => {
mockLocation('', '#/dashboard');
expect(getRedirectSuffix()).toBe('#/dashboard');
});

it('returns an empty string when neither search nor hash exist', () => {
mockLocation('', '');
expect(getRedirectSuffix()).toBe('');
});
});
15 changes: 15 additions & 0 deletions src/common/auth/getRedirectSuffix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Generates the part of the URL (query string and hash fragments) that must be kept when redirecting the user.
*
* @example
* ```ts
* // Current URL: https://example.com/?sap-theme=sap_horizon#/mcp/projects
*
* const redirectTo = getRedirectSuffix();
* // redirectTo -> "/?sap-theme=sap_horizon#/mcp/projects"
* ```
*/
export function getRedirectSuffix() {
const { search, hash } = globalThis.location;
return (search ? `/${search}` : '') + hash;
}
28 changes: 0 additions & 28 deletions src/components/Core/DarkModeSystemSwitcher.tsx

This file was deleted.

13 changes: 13 additions & 0 deletions src/components/ThemeManager.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useEffect } from 'react';
import { setTheme } from '@ui5/webcomponents-base/dist/config/Theme.js';
import { useTheme } from '../hooks/useTheme.ts';

export function ThemeManager() {
const { theme } = useTheme();

useEffect(() => {
void setTheme(theme);
}, [theme]);

return null;
}
6 changes: 3 additions & 3 deletions src/components/Yaml/YamlViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import { Button, FlexBox } from '@ui5/webcomponents-react';
import styles from './YamlViewer.module.css';
import { useToast } from '../../context/ToastContext.tsx';
import { useTranslation } from 'react-i18next';
import { useThemeMode } from '../../lib/useThemeMode.ts';
import { useTheme } from '../../hooks/useTheme.ts';
type YamlViewerProps = { yamlString: string; filename: string };
const YamlViewer: FC<YamlViewerProps> = ({ yamlString, filename }) => {
const toast = useToast();
const { t } = useTranslation();
const { isDarkMode } = useThemeMode();
const { isDarkTheme } = useTheme();
const copyToClipboard = () => {
navigator.clipboard.writeText(yamlString);
toast.show(t('yaml.copiedToClipboard'));
Expand Down Expand Up @@ -40,7 +40,7 @@ const YamlViewer: FC<YamlViewerProps> = ({ yamlString, filename }) => {
</FlexBox>
<SyntaxHighlighter
language="yaml"
style={isDarkMode ? materialDark : materialLight}
style={isDarkTheme ? materialDark : materialLight}
showLineNumbers
lineNumberStyle={{
paddingRight: '20px',
Expand Down
38 changes: 38 additions & 0 deletions src/hooks/useTheme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useSyncExternalStore } from 'react';
import { Theme } from '@ui5/webcomponents-react';

const DEFAULT_THEME_LIGHT = Theme.sap_horizon;
const DEFAULT_THEME_DARK = Theme.sap_horizon_dark;
const DARK_SAP_THEMES = new Set<string>([
Theme.sap_fiori_3_dark,
Theme.sap_fiori_3_hcb,
Theme.sap_horizon_dark,
Theme.sap_horizon_hcb,
]);

function useSystemDarkModePreference() {
return useSyncExternalStore(
(callback) => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', callback);
return () => mediaQuery.removeEventListener('change', callback);
},
() => window.matchMedia('(prefers-color-scheme: dark)').matches,
);
}

export function useTheme() {
const systemPrefersDark = useSystemDarkModePreference();
const themeFromUrl = new URL(window.location.href).searchParams.get('sap-theme');

// Theme from URL takes precedence over system settings
const theme = themeFromUrl || (systemPrefersDark ? DEFAULT_THEME_DARK : DEFAULT_THEME_LIGHT);

// For well-defined SAP themes, return if they are light or dark – unknown themes will fall back to light
const isDarkTheme = DARK_SAP_THEMES.has(theme);

return {
theme,
isDarkTheme,
};
}
7 changes: 5 additions & 2 deletions src/lib/api/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { APIError } from './error';
import { ApiConfig } from './types/apiConfig';
import { AUTH_FLOW_SESSION_KEY } from '../../common/auth/AuthCallbackHandler.tsx';
import { getRedirectSuffix } from '../../common/auth/getRedirectSuffix.ts';

const useCrateClusterHeader = 'X-use-crate';
const projectNameHeader = 'X-project';
Expand Down Expand Up @@ -48,8 +50,9 @@ export const fetchApiServer = async (

if (!res.ok) {
if (res.status === 401) {
// Unauthorized, redirect to the login page
window.location.replace('/api/auth/onboarding/login');
// Unauthorized (token expired), redirect to the login page
sessionStorage.setItem(AUTH_FLOW_SESSION_KEY, 'onboarding');
window.location.replace(`/api/auth/onboarding/login?redirectTo=${encodeURIComponent(getRedirectSuffix())}`);
}
const error = new APIError('An error occurred while fetching the data.', res.status);
error.info = await res.json();
Expand Down
7 changes: 0 additions & 7 deletions src/lib/useThemeMode.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ToastProvider } from './context/ToastContext.tsx';
import { CopyButtonProvider } from './context/CopyButtonContext.tsx';
import { FrontendConfigProvider } from './context/FrontendConfigContext.tsx';
import '@ui5/webcomponents-react/dist/Assets'; //used for loading themes
import { DarkModeSystemSwitcher } from './components/Core/DarkModeSystemSwitcher.tsx';
import { ThemeManager } from './components/ThemeManager.tsx';
import '.././i18n.ts';
import './utils/i18n/timeAgo';
import { ErrorBoundary, FallbackProps } from 'react-error-boundary';
Expand Down Expand Up @@ -49,7 +49,7 @@ export function createApp() {
<ApolloClientProvider>
<App />
</ApolloClientProvider>
<DarkModeSystemSwitcher />
<ThemeManager />
</SWRConfig>
</CopyButtonProvider>
</ToastProvider>
Expand Down
4 changes: 2 additions & 2 deletions src/spaces/mcp/auth/AuthContextMcp.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createContext, useState, useEffect, ReactNode, use } from 'react';
import { MeResponseSchema } from './auth.schemas';
import { AUTH_FLOW_SESSION_KEY } from '../../../common/auth/AuthCallbackHandler.tsx';
import { getRedirectSuffix } from '../../../common/auth/getRedirectSuffix.ts';

interface AuthContextMcpType {
isLoading: boolean;
Expand Down Expand Up @@ -55,8 +56,7 @@ export function AuthProviderMcp({ children }: { children: ReactNode }) {

const login = () => {
sessionStorage.setItem(AUTH_FLOW_SESSION_KEY, 'mcp');

window.location.replace(`/api/auth/mcp/login?redirectTo=${encodeURIComponent(window.location.hash)}`);
window.location.replace(`/api/auth/mcp/login?redirectTo=${encodeURIComponent(getRedirectSuffix())}`);
};

return <AuthContextMcp value={{ isLoading, isAuthenticated, error, login }}>{children}</AuthContextMcp>;
Expand Down
4 changes: 2 additions & 2 deletions src/spaces/onboarding/auth/AuthContextOnboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createContext, useState, useEffect, ReactNode, use } from 'react';
import { MeResponseSchema, User } from './auth.schemas';
import { AUTH_FLOW_SESSION_KEY } from '../../../common/auth/AuthCallbackHandler.tsx';
import * as Sentry from '@sentry/react';
import { getRedirectSuffix } from '../../../common/auth/getRedirectSuffix.ts';

interface AuthContextOnboardingType {
isLoading: boolean;
Expand Down Expand Up @@ -67,8 +68,7 @@ export function AuthProviderOnboarding({ children }: { children: ReactNode }) {

const login = () => {
sessionStorage.setItem(AUTH_FLOW_SESSION_KEY, 'onboarding');

window.location.replace(`/api/auth/onboarding/login?redirectTo=${encodeURIComponent(window.location.hash)}`);
window.location.replace(`/api/auth/onboarding/login?redirectTo=${encodeURIComponent(getRedirectSuffix())}`);
};

const logout = async () => {
Expand Down
Loading