Skip to content
Closed
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
15 changes: 11 additions & 4 deletions src/app/[lang]/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Metadata } from 'next';
import { cookies } from 'next/headers';
import { notFound } from 'next/navigation';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { RouteProgressProvider } from '@/features/Navigation/RouteProgress';
import { resolveTheme, THEME_COOKIE, ThemeProvider } from '@/features/Theme';
import { locales } from '@/utils/locales';
import '../globals.css';

Expand All @@ -27,12 +29,17 @@ export default async function RootLayout({

const messages = await getMessages({ locale: lang });

const cookieStore = await cookies();
const theme = resolveTheme(cookieStore.get(THEME_COOKIE)?.value);

return (
<html lang={lang} suppressHydrationWarning>
<html lang={lang} data-theme={theme} suppressHydrationWarning>
<body suppressHydrationWarning>
<NextIntlClientProvider locale={lang} messages={messages}>
<RouteProgressProvider>{children}</RouteProgressProvider>
</NextIntlClientProvider>
<ThemeProvider initialTheme={theme}>
<NextIntlClientProvider locale={lang} messages={messages}>
<RouteProgressProvider>{children}</RouteProgressProvider>
</NextIntlClientProvider>
</ThemeProvider>
</body>
</html>
);
Expand Down
19 changes: 18 additions & 1 deletion src/app/[lang]/settings/SettingsRouteClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type SettingsFormValues,
SettingsPage,
} from '@/features/Settings/SettingsPage';
import { locales } from '@/utils/locales';

type SettingsRouteClientProps = {
defaultEmail: string;
Expand All @@ -28,7 +29,7 @@ type SettingsRouteClientProps = {
userDisplayName: string;
};

const saveSettings = async (data: SettingsFormValues) => {
const postSettings = async (data: SettingsFormValues) => {
const response = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
Expand All @@ -40,6 +41,9 @@ const saveSettings = async (data: SettingsFormValues) => {
}
};

const isSupportedLocale = (value: string): value is (typeof locales)[number] =>
locales.includes(value as (typeof locales)[number]);

const downloadAccountData = async () => {
const response = await fetch('/api/account/export');

Expand Down Expand Up @@ -67,6 +71,19 @@ export const SettingsRouteClient = ({
userDisplayName,
}: SettingsRouteClientProps) => {
const router = useRouteProgressRouter();

const saveSettings = async (data: SettingsFormValues) => {
await postSettings(data);

if (
isSupportedLocale(data.applicationLanguage) &&
data.applicationLanguage !== locale
) {
router.push(`/${data.applicationLanguage}/settings`);
router.refresh();
}
};

const defaultSettings: SettingsFormValues = {
isPublic: initialPrivacySettings?.isPublic ?? true,
allowAnonymousCopy: initialPrivacySettings?.allowAnonymousCopy ?? true,
Expand Down
38 changes: 36 additions & 2 deletions src/app/api/auth/discord/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
import { type NextRequest, NextResponse } from 'next/server';
import { upsertDiscordUser } from '@/db';
import { getUserSettingsByDiscordUserId, upsertDiscordUser } from '@/db';
import { resolveTheme, THEME_COOKIE } from '@/features/Theme';
import {
AUTH_ERROR_PARAM,
clearOAuthStateCookie,
normalizeDiscordUser,
readOAuthStateCookie,
setSessionCookie,
} from '@/lib/auth';
import { locales } from '@/utils/locales';

const THEME_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;

const isSupportedLocale = (value: string): value is (typeof locales)[number] =>
locales.includes(value as (typeof locales)[number]);

const applyPreferredLocale = (redirectTo: string, preferred: string) => {
if (!isSupportedLocale(preferred)) {
return redirectTo;
}

const segments = redirectTo.split('/');
if (segments[1] && isSupportedLocale(segments[1])) {
segments[1] = preferred;
return segments.join('/');
}

return `/${preferred}${redirectTo}`;
};

type DiscordTokenResponse = {
access_token?: string;
Expand Down Expand Up @@ -112,12 +133,25 @@ export const GET = async (request: NextRequest) => {
const currentUser = normalizeDiscordUser(discordUser);
await upsertDiscordUser(currentUser);

const settings = await getUserSettingsByDiscordUserId(currentUser.id);
const destination = settings
? applyPreferredLocale(redirectTo, settings.applicationLanguage)
: redirectTo;

const response = NextResponse.redirect(
new URL(redirectTo, request.nextUrl.origin),
new URL(destination, request.nextUrl.origin),
);
await setSessionCookie(response, currentUser);
clearOAuthStateCookie(response);

if (settings) {
response.cookies.set(THEME_COOKIE, resolveTheme(settings.theme), {
path: '/',
maxAge: THEME_COOKIE_MAX_AGE,
sameSite: 'lax',
});
}

return response;
} catch {
return redirectWithError(request, redirectTo, 'oauth_failed');
Expand Down
35 changes: 35 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,41 @@
--font-DM: "DM Sans", sans-serif;
}

html[data-theme="light"] {
--color-primary: #2c3a49;
--color-primary-light: #1d2731;
--color-primary-lighter: #0f161d;
--color-primary-dark: #5b6b7b;
--color-primary-darker: #d9e3ee;

--color-background-dark: #ffffff;
--color-background-light: #6b7280;
--color-background-darker: #eef1f5;
--color-background-main: #f3f5f8;
--color-background-lighter: #9aa3ae;
--color-background-darkest: #e2e6ec;
}

html[data-theme="light"] body {
color: #1a1d22;
}

html[data-theme="light"] .text-white {
color: #1a1d22;
}

html[data-theme="light"] .border-white\/10 {
border-color: rgba(0, 0, 0, 0.08);
}

html[data-theme="light"] .bg-white\/10 {
background-color: rgba(0, 0, 0, 0.06);
}

html[data-theme="light"] .hover\:bg-\[\#161617\]:hover {
background-color: #e7eaf0;
}

@keyframes slideDown {
from {
transform: translateY(-10px);
Expand Down
21 changes: 15 additions & 6 deletions src/features/Settings/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import {
TextInput,
Toggle,
} from '@/components/Form';
import { languageOptions, type TimeFormat } from '@/constants/languages';
import { getLanguageName, type TimeFormat } from '@/constants/languages';
import { useTheme } from '@/features/Theme';
import { locales } from '@/utils/locales';
import { CompareTable } from './CompareTable';
import { type SettingsFormValues, settingsSchema } from './schema';

Expand Down Expand Up @@ -108,6 +110,7 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({
}) => {
const t = useTranslations('Settings');
const currentLocale = useLocale();
const { theme: committedTheme, setTheme, previewTheme } = useTheme();
const [activeSection, setActiveSection] = useState<SectionId>('account');
const [exportStatus, setExportStatus] = useState<
'idle' | 'loading' | 'success' | 'error'
Expand All @@ -121,9 +124,10 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({
const initialValues: SettingsFormValues = useMemo(
() => ({
...defaultValues,
theme: committedTheme,
timeFormat: defaultValues.timeFormat || getStoredTimeFormat(),
}),
[defaultValues],
[defaultValues, committedTheme],
);

const {
Expand Down Expand Up @@ -162,6 +166,7 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({
window.dispatchEvent(new Event('timeFormatChanged'));
}

setTheme(data.theme);
reset(data);
} catch {
setSaveStatus('error');
Expand All @@ -176,6 +181,7 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({

const handleDiscard = () => {
reset();
previewTheme(committedTheme);
setExportStatus('idle');
setDeleteStatus('idle');
setSaveStatus('idle');
Expand Down Expand Up @@ -211,9 +217,9 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({

const localizedLanguageOptions = useMemo(
() =>
languageOptions(currentLocale).map((option) => ({
...option,
label: `${option.label} (${option.value.toUpperCase()})`,
locales.map((locale) => ({
value: locale,
label: `${getLanguageName(locale, currentLocale)} (${locale.toUpperCase()})`,
})),
[currentLocale],
);
Expand Down Expand Up @@ -537,7 +543,10 @@ export const SettingsPage: React.FC<SettingsPageProps> = ({
render={({ field }) => (
<Select
options={themeOptions}
onValueChange={field.onChange}
onValueChange={(value) => {
field.onChange(value);
previewTheme(value as 'dark' | 'light');
}}
value={field.value}
ariaLabel={t('themeLabel')}
className="w-[170px]"
Expand Down
65 changes: 65 additions & 0 deletions src/features/Theme/ThemeProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use client';

import {
createContext,
useCallback,
useContext,
useMemo,
useState,
} from 'react';
import { THEME_COOKIE, type Theme } from './theme';

const THEME_MAX_AGE = 60 * 60 * 24 * 365;

type ThemeContextValue = {
theme: Theme;
setTheme: (theme: Theme) => void;
previewTheme: (theme: Theme) => void;
};

const applyTheme = (theme: Theme) => {
if (typeof document === 'undefined') return;
document.documentElement.dataset.theme = theme;
};

const ThemeContext = createContext<ThemeContextValue>({
theme: 'dark',
setTheme: applyTheme,
previewTheme: applyTheme,
});

export const ThemeProvider = ({
initialTheme,
children,
}: {
initialTheme: Theme;
children: React.ReactNode;
}) => {
const [theme, setThemeState] = useState<Theme>(initialTheme);

const setTheme = useCallback((next: Theme) => {
setThemeState(next);
applyTheme(next);

if (typeof document !== 'undefined') {
document.cookie = `${THEME_COOKIE}=${next}; path=/; max-age=${THEME_MAX_AGE}; samesite=lax`;
}

try {
localStorage.setItem(THEME_COOKIE, next);
} catch {}
}, []);

const previewTheme = useCallback((next: Theme) => applyTheme(next), []);

const value = useMemo(
() => ({ theme, setTheme, previewTheme }),
[theme, setTheme, previewTheme],
);

return (
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
);
};

export const useTheme = () => useContext(ThemeContext);
2 changes: 2 additions & 0 deletions src/features/Theme/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { ThemeProvider, useTheme } from './ThemeProvider';
export { resolveTheme, THEME_COOKIE, type Theme } from './theme';
6 changes: 6 additions & 0 deletions src/features/Theme/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type Theme = 'dark' | 'light';

export const THEME_COOKIE = 'polycord_theme';

export const resolveTheme = (value: string | undefined): Theme =>
value === 'light' ? 'light' : 'dark';