64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
"use client"
|
||
|
||
import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
|
||
import Dexie from "dexie"
|
||
|
||
interface DatabaseContextType {
|
||
isReady: boolean
|
||
error: Error | null
|
||
}
|
||
|
||
const DatabaseContext = createContext<DatabaseContextType>({
|
||
isReady: false,
|
||
error: null,
|
||
})
|
||
|
||
export function DatabaseProvider({ children }: { children: ReactNode }) {
|
||
const [isReady, setIsReady] = useState(false)
|
||
const [error, setError] = useState<Error | null>(null)
|
||
|
||
useEffect(() => {
|
||
const initDatabase = async () => {
|
||
try {
|
||
// 动态导入数据库模块
|
||
const { db } = await import("@/lib/db/schema")
|
||
const { seedDatabase } = await import("@/lib/db/seed")
|
||
|
||
await db.open()
|
||
await seedDatabase()
|
||
setIsReady(true)
|
||
} catch (err) {
|
||
console.error("[v0] Database init error:", err)
|
||
// 如果IndexedDB不可用,仍然允许应用运行
|
||
if (err instanceof Dexie.MissingAPIError) {
|
||
console.warn("[v0] IndexedDB not available, using fallback")
|
||
setIsReady(true)
|
||
} else {
|
||
setError(err as Error)
|
||
// 即使出错也允许应用运行
|
||
setIsReady(true)
|
||
}
|
||
}
|
||
}
|
||
|
||
initDatabase()
|
||
}, [])
|
||
|
||
if (!isReady) {
|
||
return (
|
||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||
<div className="text-center">
|
||
<div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
|
||
<p className="text-muted-foreground text-sm">正在初始化...</p>
|
||
</div>
|
||
</div>
|
||
)
|
||
}
|
||
|
||
return <DatabaseContext.Provider value={{ isReady, error }}>{children}</DatabaseContext.Provider>
|
||
}
|
||
|
||
export function useDatabaseContext() {
|
||
return useContext(DatabaseContext)
|
||
}
|