Skip to content

An AI-powered search engine with a generative UI

Fix theme and sidebar hydration

Yoshiki Miuraf2d83a10c297
diff --git a/bun.lock b/bun.lock
index 3885740c..67dbe420 100644
--- a/bun.lock
+++ b/bun.lock
@@ -60,7 +60,6 @@
"katex": "^0.16.10",
"langfuse-vercel": "^3.38.4",
"next": "^16.2.6",
- "next-themes": "0.4.6",
"node-html-parser": "^6.1.13",
"postgres": "^3.4.5",
"react": "^19.2.0",
@@ -1801,8 +1800,6 @@
"next": ["[email protected]", "", { "dependencies": { "@next/env": "16.2.6", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.2.6", "@next/swc-darwin-x64": "16.2.6", "@next/swc-linux-arm64-gnu": "16.2.6", "@next/swc-linux-arm64-musl": "16.2.6", "@next/swc-linux-x64-gnu": "16.2.6", "@next/swc-linux-x64-musl": "16.2.6", "@next/swc-win32-arm64-msvc": "16.2.6", "@next/swc-win32-x64-msvc": "16.2.6", "sharp": "^0.34.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-qOVgKJg1+At15NpeUP+eJgCHvTCgXsogweq87Ri/Ix7PkqQHg4sdaXmSFqKlgaIXE4kW0g25LE68W87UANlHtw=="],
- "next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
-
"node-fetch": ["[email protected]", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"node-html-parser": ["[email protected]", "", { "dependencies": { "css-select": "^5.1.0", "he": "1.2.0" } }, "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg=="],
diff --git a/components/account-settings-dialog.tsx b/components/account-settings-dialog.tsx
index 3a84ff3a..6a95e091 100644
--- a/components/account-settings-dialog.tsx
+++ b/components/account-settings-dialog.tsx
@@ -2,7 +2,6 @@
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
-import { useTheme } from 'next-themes'
import type { User } from '@supabase/supabase-js'
import {
@@ -38,6 +37,8 @@ import {
import { Separator } from '@/components/ui/separator'
import { Spinner } from '@/components/ui/spinner'
+import { useTheme } from '@/components/theme-provider'
+
interface AccountSettingsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx
index e867c06c..6f3dc85b 100644
--- a/components/app-sidebar.tsx
+++ b/components/app-sidebar.tsx
@@ -1,8 +1,6 @@
import { Suspense } from 'react'
import Link from 'next/link'
-import { IconPlus as Plus } from '@tabler/icons-react'
-
import { cn } from '@/lib/utils'
import {
@@ -10,14 +8,13 @@ import {
SidebarContent,
SidebarHeader,
SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
SidebarRail,
SidebarTrigger
} from '@/components/ui/sidebar'
import { ChatHistorySection } from './sidebar/chat-history-section'
import { ChatHistorySkeleton } from './sidebar/chat-history-skeleton'
+import { NewChatMenuItem } from './sidebar/new-chat-menu-item'
import { IconLogo } from './ui/icons'
export default function AppSidebar() {
@@ -32,14 +29,7 @@ export default function AppSidebar() {
</SidebarHeader>
<SidebarContent className="flex flex-col px-2 py-4 h-full">
<SidebarMenu>
- <SidebarMenuItem>
- <SidebarMenuButton asChild>
- <Link href="/" className="flex items-center gap-2">
- <Plus className="size-4" />
- <span>New</span>
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
+ <NewChatMenuItem />
</SidebarMenu>
<div className="flex-1 overflow-y-auto">
<Suspense fallback={<ChatHistorySkeleton />}>
diff --git a/components/keyboard-shortcut-handler.tsx b/components/keyboard-shortcut-handler.tsx
index ef064346..0eb9d3af 100644
--- a/components/keyboard-shortcut-handler.tsx
+++ b/components/keyboard-shortcut-handler.tsx
@@ -1,7 +1,5 @@
'use client'
-import { useTheme } from 'next-themes'
-
import { toast } from 'sonner'
import { SHORTCUT_EVENTS, SHORTCUTS } from '@/lib/keyboard-shortcuts'
@@ -12,6 +10,7 @@ import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
import { useSidebar } from './ui/sidebar'
import { KeyboardShortcutDialog } from './keyboard-shortcut-dialog'
+import { useTheme } from './theme-provider'
const THEME_CYCLE: Record<string, string> = {
dark: 'light',
diff --git a/components/sidebar/new-chat-menu-item.tsx b/components/sidebar/new-chat-menu-item.tsx
new file mode 100644
index 00000000..1e794db8
--- /dev/null
+++ b/components/sidebar/new-chat-menu-item.tsx
@@ -0,0 +1,20 @@
+'use client'
+
+import Link from 'next/link'
+
+import { IconPlus as Plus } from '@tabler/icons-react'
+
+import { SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar'
+
+export function NewChatMenuItem() {
+ return (
+ <SidebarMenuItem>
+ <SidebarMenuButton asChild>
+ <Link href="/" className="flex items-center gap-2">
+ <Plus className="size-4" />
+ <span>New</span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ )
+}
diff --git a/components/theme-menu-items.tsx b/components/theme-menu-items.tsx
index 924b126f..1b26eae1 100644
--- a/components/theme-menu-items.tsx
+++ b/components/theme-menu-items.tsx
@@ -1,7 +1,5 @@
'use client'
-import { useTheme } from 'next-themes'
-
import {
IconDeviceLaptop as Laptop,
IconMoon as Moon,
@@ -10,6 +8,8 @@ import {
import { DropdownMenuItem } from '@/components/ui/dropdown-menu'
+import { useTheme } from '@/components/theme-provider'
+
export function ThemeMenuItems() {
const { setTheme } = useTheme()
diff --git a/components/theme-provider.tsx b/components/theme-provider.tsx
index 70d5ec2c..15503091 100644
--- a/components/theme-provider.tsx
+++ b/components/theme-provider.tsx
@@ -1,9 +1,526 @@
'use client'
-import * as React from 'react'
-import { ThemeProvider as NextThemesProvider } from 'next-themes'
-import { type ThemeProviderProps } from 'next-themes'
+import type {
+ Dispatch,
+ PropsWithChildren,
+ ScriptHTMLAttributes,
+ SetStateAction
+} from 'react'
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from 'react'
+import { useServerInsertedHTML } from 'next/navigation'
-export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
- return <NextThemesProvider {...props}>{children}</NextThemesProvider>
+type SystemTheme = 'dark' | 'light'
+type DataAttribute = `data-${string}`
+type Attribute = DataAttribute | 'class'
+type ThemeAttribute = Attribute | Attribute[]
+type ValueObject = Record<string, string>
+
+interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
+ [dataAttribute: DataAttribute]: unknown
+}
+
+export interface UseThemeProps {
+ themes: string[]
+ forcedTheme?: string
+ setTheme: Dispatch<SetStateAction<string>>
+ theme?: string
+ resolvedTheme?: string
+ systemTheme?: SystemTheme
+}
+
+export interface ThemeProviderProps extends PropsWithChildren {
+ themes?: string[]
+ forcedTheme?: string
+ enableSystem?: boolean
+ disableTransitionOnChange?: boolean
+ enableColorScheme?: boolean
+ storageKey?: string
+ defaultTheme?: string
+ attribute?: ThemeAttribute
+ value?: ValueObject
+ nonce?: string
+ scriptProps?: ScriptProps
+}
+
+const DEFAULT_THEMES = ['light', 'dark']
+const COLOR_SCHEME_THEMES = ['light', 'dark']
+const SYSTEM_THEME_MEDIA = '(prefers-color-scheme: dark)'
+
+const fallbackThemeContext: UseThemeProps = {
+ setTheme: () => {},
+ themes: []
+}
+
+const ThemeContext = createContext<UseThemeProps | undefined>(undefined)
+
+export function useTheme() {
+ return useContext(ThemeContext) ?? fallbackThemeContext
+}
+
+export function ThemeProvider(props: ThemeProviderProps) {
+ const context = useContext(ThemeContext)
+
+ if (context) {
+ return <>{props.children}</>
+ }
+
+ return <ThemeProviderInner {...props} />
+}
+
+function ThemeProviderInner({
+ attribute = 'data-theme',
+ children,
+ defaultTheme,
+ disableTransitionOnChange = false,
+ enableColorScheme = true,
+ enableSystem = true,
+ forcedTheme,
+ nonce,
+ scriptProps,
+ storageKey = 'theme',
+ themes = DEFAULT_THEMES,
+ value
+}: ThemeProviderProps) {
+ const resolvedDefaultTheme =
+ defaultTheme ?? (enableSystem ? 'system' : 'light')
+ const [theme, setThemeState] = useState<string | undefined>(
+ resolvedDefaultTheme
+ )
+ const [systemTheme, setSystemTheme] = useState<SystemTheme | undefined>()
+ const hasSyncedTheme = useRef(false)
+ const hasInsertedThemeScript = useRef(false)
+ const themeRef = useRef<string | undefined>(resolvedDefaultTheme)
+
+ const applyThemeWithConfig = useCallback(
+ (nextTheme?: string) => {
+ applyTheme(nextTheme, {
+ attribute,
+ defaultTheme: resolvedDefaultTheme,
+ disableTransitionOnChange,
+ enableColorScheme,
+ enableSystem,
+ nonce,
+ themes,
+ value
+ })
+ },
+ [
+ attribute,
+ disableTransitionOnChange,
+ enableColorScheme,
+ enableSystem,
+ nonce,
+ resolvedDefaultTheme,
+ themes,
+ value
+ ]
+ )
+
+ const setTheme = useCallback<Dispatch<SetStateAction<string>>>(
+ nextThemeOrUpdater => {
+ const nextTheme =
+ typeof nextThemeOrUpdater === 'function'
+ ? nextThemeOrUpdater(themeRef.current ?? resolvedDefaultTheme)
+ : nextThemeOrUpdater
+
+ themeRef.current = nextTheme
+ setThemeState(nextTheme)
+
+ try {
+ window.localStorage.setItem(storageKey, nextTheme)
+ } catch {}
+
+ if (hasSyncedTheme.current) {
+ applyThemeWithConfig(forcedTheme ?? nextTheme)
+ }
+ },
+ [applyThemeWithConfig, forcedTheme, resolvedDefaultTheme, storageKey]
+ )
+
+ useServerInsertedHTML(() => {
+ if (hasInsertedThemeScript.current) {
+ return null
+ }
+
+ hasInsertedThemeScript.current = true
+
+ const scriptNonce = nonce ?? scriptProps?.nonce
+
+ return (
+ <script
+ {...scriptProps}
+ nonce={scriptNonce}
+ suppressHydrationWarning
+ dangerouslySetInnerHTML={{
+ __html: getThemeScript({
+ attribute,
+ defaultTheme: resolvedDefaultTheme,
+ enableColorScheme,
+ enableSystem,
+ forcedTheme,
+ storageKey,
+ themes,
+ value
+ })
+ }}
+ />
+ )
+ })
+
+ useEffect(() => {
+ if (!hasSyncedTheme.current) {
+ return
+ }
+
+ applyThemeWithConfig(forcedTheme ?? theme)
+ }, [applyThemeWithConfig, forcedTheme, theme])
+
+ useEffect(() => {
+ const mediaQuery = window.matchMedia(SYSTEM_THEME_MEDIA)
+
+ const syncTheme = (nextTheme: string) => {
+ themeRef.current = nextTheme
+ setThemeState(nextTheme)
+ applyThemeWithConfig(forcedTheme ?? nextTheme)
+ }
+
+ const handleMediaChange = (event: MediaQueryList | MediaQueryListEvent) => {
+ const nextSystemTheme = getSystemTheme(event)
+
+ setSystemTheme(nextSystemTheme)
+
+ if ((forcedTheme ?? themeRef.current) === 'system' && enableSystem) {
+ applyThemeWithConfig(forcedTheme ?? themeRef.current)
+ }
+ }
+
+ const handleStorage = (event: StorageEvent) => {
+ if (event.key !== storageKey) {
+ return
+ }
+
+ syncTheme(event.newValue ?? resolvedDefaultTheme)
+ }
+
+ let isMounted = true
+
+ window.queueMicrotask(() => {
+ if (!isMounted) {
+ return
+ }
+
+ setSystemTheme(getSystemTheme(mediaQuery))
+ syncTheme(getStoredTheme(storageKey, resolvedDefaultTheme))
+ hasSyncedTheme.current = true
+ })
+
+ addMediaListener(mediaQuery, handleMediaChange)
+ window.addEventListener('storage', handleStorage)
+
+ return () => {
+ isMounted = false
+ removeMediaListener(mediaQuery, handleMediaChange)
+ window.removeEventListener('storage', handleStorage)
+ }
+ }, [
+ applyThemeWithConfig,
+ enableSystem,
+ forcedTheme,
+ resolvedDefaultTheme,
+ storageKey
+ ])
+
+ const themesWithSystem = useMemo(
+ () => (enableSystem ? [...themes, 'system'] : themes),
+ [enableSystem, themes]
+ )
+
+ const contextValue = useMemo<UseThemeProps>(
+ () => ({
+ forcedTheme,
+ resolvedTheme: theme === 'system' ? systemTheme : theme,
+ setTheme,
+ systemTheme: enableSystem ? systemTheme : undefined,
+ theme,
+ themes: themesWithSystem
+ }),
+ [enableSystem, forcedTheme, setTheme, systemTheme, theme, themesWithSystem]
+ )
+
+ return (
+ <ThemeContext.Provider value={contextValue}>
+ {children}
+ </ThemeContext.Provider>
+ )
+}
+
+function getStoredTheme(storageKey: string, defaultTheme: string) {
+ try {
+ return window.localStorage.getItem(storageKey) ?? defaultTheme
+ } catch {
+ return defaultTheme
+ }
+}
+
+function getSystemTheme(
+ mediaQuery?: MediaQueryList | MediaQueryListEvent
+): SystemTheme {
+ const matches =
+ mediaQuery?.matches ?? window.matchMedia(SYSTEM_THEME_MEDIA).matches
+
+ return matches ? 'dark' : 'light'
+}
+
+function addMediaListener(
+ mediaQuery: MediaQueryList,
+ listener: (event: MediaQueryListEvent) => void
+) {
+ const legacyMediaQuery = mediaQuery as MediaQueryList & {
+ addListener?: (listener: (event: MediaQueryListEvent) => void) => void
+ }
+
+ if (typeof legacyMediaQuery.addEventListener === 'function') {
+ mediaQuery.addEventListener('change', listener)
+ return
+ }
+
+ legacyMediaQuery.addListener?.(listener)
+}
+
+function removeMediaListener(
+ mediaQuery: MediaQueryList,
+ listener: (event: MediaQueryListEvent) => void
+) {
+ const legacyMediaQuery = mediaQuery as MediaQueryList & {
+ removeListener?: (listener: (event: MediaQueryListEvent) => void) => void
+ }
+
+ if (typeof legacyMediaQuery.removeEventListener === 'function') {
+ mediaQuery.removeEventListener('change', listener)
+ return
+ }
+
+ legacyMediaQuery.removeListener?.(listener)
+}
+
+function applyTheme(
+ theme: string | undefined,
+ {
+ attribute,
+ defaultTheme,
+ disableTransitionOnChange,
+ enableColorScheme,
+ enableSystem,
+ nonce,
+ themes,
+ value
+ }: {
+ attribute: ThemeAttribute
+ defaultTheme: string
+ disableTransitionOnChange: boolean
+ enableColorScheme: boolean
+ enableSystem: boolean
+ nonce?: string
+ themes: string[]
+ value?: ValueObject
+ }
+) {
+ if (!theme || typeof document === 'undefined') {
+ return
+ }
+
+ const root = document.documentElement
+ const resolvedTheme =
+ theme === 'system' && enableSystem ? getSystemTheme() : theme
+ const themeValue = value?.[resolvedTheme] ?? resolvedTheme
+ const restoreTransitions = disableTransitionOnChange
+ ? disableTransitions(nonce)
+ : undefined
+
+ for (const attr of getAttributes(attribute)) {
+ if (attr === 'class') {
+ const classesToRemove = getThemeClassNames(themes, value)
+
+ if (classesToRemove.length > 0) {
+ root.classList.remove(...classesToRemove)
+ }
+
+ if (themeValue) {
+ root.classList.add(themeValue)
+ }
+ } else if (attr.startsWith('data-')) {
+ if (themeValue) {
+ root.setAttribute(attr, themeValue)
+ } else {
+ root.removeAttribute(attr)
+ }
+ }
+ }
+
+ if (enableColorScheme) {
+ const fallback = COLOR_SCHEME_THEMES.includes(defaultTheme)
+ ? defaultTheme
+ : undefined
+ const colorScheme = COLOR_SCHEME_THEMES.includes(resolvedTheme)
+ ? resolvedTheme
+ : fallback
+
+ if (colorScheme) {
+ root.style.colorScheme = colorScheme
+ }
+ }
+
+ restoreTransitions?.()
+}
+
+function getAttributes(attribute: ThemeAttribute) {
+ return Array.isArray(attribute) ? attribute : [attribute]
+}
+
+function getThemeClassNames(themes: string[], value?: ValueObject) {
+ return themes.map(theme => value?.[theme] ?? theme).filter(Boolean)
+}
+
+function disableTransitions(nonce?: string) {
+ const style = document.createElement('style')
+
+ if (nonce) {
+ style.setAttribute('nonce', nonce)
+ }
+
+ style.appendChild(
+ document.createTextNode(
+ '*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'
+ )
+ )
+
+ document.head.appendChild(style)
+
+ return () => {
+ window.getComputedStyle(document.body)
+ window.setTimeout(() => {
+ document.head.removeChild(style)
+ }, 1)
+ }
+}
+
+function getThemeScript({
+ attribute,
+ defaultTheme,
+ enableColorScheme,
+ enableSystem,
+ forcedTheme,
+ storageKey,
+ themes,
+ value
+}: {
+ attribute: ThemeAttribute
+ defaultTheme: string
+ enableColorScheme: boolean
+ enableSystem: boolean
+ forcedTheme?: string
+ storageKey: string
+ themes: string[]
+ value?: ValueObject
+}) {
+ const args = JSON.stringify([
+ attribute,
+ storageKey,
+ defaultTheme,
+ forcedTheme,
+ themes,
+ value,
+ enableSystem,
+ enableColorScheme
+ ]).replace(/</g, '\\u003c')
+
+ return `(${themeScript.toString()}).apply(null, ${args})`
+}
+
+function themeScript(
+ attribute: ThemeAttribute,
+ storageKey: string,
+ defaultTheme: string,
+ forcedTheme: string | undefined,
+ themes: string[],
+ value: ValueObject | undefined,
+ enableSystem: boolean,
+ enableColorScheme: boolean
+) {
+ const root = document.documentElement
+ const colorSchemeThemes = ['light', 'dark']
+
+ function getSystemTheme() {
+ return window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light'
+ }
+
+ function getAttributes() {
+ return Array.isArray(attribute) ? attribute : [attribute]
+ }
+
+ function applyTheme(theme: string | undefined) {
+ if (!theme) {
+ return
+ }
+
+ const resolvedTheme =
+ theme === 'system' && enableSystem ? getSystemTheme() : theme
+ const themeValue = value?.[resolvedTheme] ?? resolvedTheme
+
+ for (const attr of getAttributes()) {
+ if (attr === 'class') {
+ const classesToRemove = themes
+ .map(themeName => value?.[themeName] ?? themeName)
+ .filter(Boolean)
+
+ if (classesToRemove.length > 0) {
+ root.classList.remove(...classesToRemove)
+ }
+
+ if (themeValue) {
+ root.classList.add(themeValue)
+ }
+ } else if (attr.startsWith('data-')) {
+ if (themeValue) {
+ root.setAttribute(attr, themeValue)
+ } else {
+ root.removeAttribute(attr)
+ }
+ }
+ }
+
+ if (enableColorScheme) {
+ const fallback = colorSchemeThemes.includes(defaultTheme)
+ ? defaultTheme
+ : undefined
+ const colorScheme = colorSchemeThemes.includes(resolvedTheme)
+ ? resolvedTheme
+ : fallback
+
+ if (colorScheme) {
+ root.style.colorScheme = colorScheme
+ }
+ }
+ }
+
+ if (forcedTheme) {
+ applyTheme(forcedTheme)
+ return
+ }
+
+ try {
+ applyTheme(localStorage.getItem(storageKey) ?? defaultTheme)
+ } catch {
+ applyTheme(defaultTheme)
+ }
}
diff --git a/components/ui/sonner.tsx b/components/ui/sonner.tsx
index a766fcee..f86085c5 100644
--- a/components/ui/sonner.tsx
+++ b/components/ui/sonner.tsx
@@ -1,9 +1,9 @@
'use client'
-import { useTheme } from 'next-themes'
-
import { Toaster as Sonner } from 'sonner'
+import { useTheme } from '@/components/theme-provider'
+
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
diff --git a/package.json b/package.json
index 5bfb8e71..255faf26 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,6 @@
"katex": "^0.16.10",
"langfuse-vercel": "^3.38.4",
"next": "^16.2.6",
- "next-themes": "0.4.6",
"node-html-parser": "^6.1.13",
"postgres": "^3.4.5",
"react": "^19.2.0",