- Replace mobile placeholder with Expo Router app (tabs, playback, auth, library) - Move Convex backend to @otunes/convex for web and mobile reuse - Update web app imports and API routes to use shared package
81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage"
|
|
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react"
|
|
|
|
import {
|
|
clearServerConfig,
|
|
loadServerConfig,
|
|
parseServerHostname,
|
|
saveServerConfig,
|
|
type ServerConfig,
|
|
} from "@/lib/server-config"
|
|
|
|
type ServerConfigContextValue = {
|
|
config: ServerConfig | null
|
|
isLoading: boolean
|
|
setServerHostname: (hostname: string) => Promise<boolean>
|
|
clearServer: () => Promise<void>
|
|
}
|
|
|
|
const ServerConfigContext = createContext<ServerConfigContextValue | null>(null)
|
|
|
|
export function ServerConfigProvider({ children }: { children: ReactNode }) {
|
|
const [config, setConfig] = useState<ServerConfig | null>(null)
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
void loadServerConfig((key) => AsyncStorage.getItem(key)).then((loaded) => {
|
|
if (!cancelled) {
|
|
setConfig(loaded)
|
|
setIsLoading(false)
|
|
}
|
|
})
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [])
|
|
|
|
const setServerHostname = useCallback(async (hostname: string) => {
|
|
const parsed = parseServerHostname(hostname)
|
|
if (!parsed) return false
|
|
await saveServerConfig(
|
|
(key, value) => AsyncStorage.setItem(key, value),
|
|
parsed
|
|
)
|
|
setConfig(parsed)
|
|
return true
|
|
}, [])
|
|
|
|
const clearServer = useCallback(async () => {
|
|
await clearServerConfig((key) => AsyncStorage.removeItem(key))
|
|
setConfig(null)
|
|
}, [])
|
|
|
|
const value = useMemo(
|
|
() => ({ config, isLoading, setServerHostname, clearServer }),
|
|
[config, isLoading, setServerHostname, clearServer]
|
|
)
|
|
|
|
return (
|
|
<ServerConfigContext.Provider value={value}>
|
|
{children}
|
|
</ServerConfigContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useServerConfig() {
|
|
const context = useContext(ServerConfigContext)
|
|
if (!context) {
|
|
throw new Error("useServerConfig must be used within ServerConfigProvider")
|
|
}
|
|
return context
|
|
}
|