fediversion/frontend/contexts/vertical-context.tsx
fullsizemalt 9e927c114e
Some checks failed
Deploy Fediversion / deploy (push) Failing after 1s
fix: refactor VERTICALS constant to config file to fix server build
2025-12-28 21:26:08 -08:00

87 lines
2.8 KiB
TypeScript

"use client"
import { createContext, useContext, useState, useEffect, ReactNode } from "react"
import { usePathname } from "next/navigation"
import { VERTICALS, Vertical, VerticalSlug } from "@/config/verticals"
interface VerticalContextType {
current: Vertical
setCurrent: (slug: VerticalSlug) => void
all: readonly Vertical[]
}
const VerticalContext = createContext<VerticalContextType | null>(null)
export function VerticalProvider({ children }: { children: ReactNode }) {
const pathname = usePathname()
// Detect vertical from URL path
const getVerticalFromPath = (): Vertical => {
const segments = pathname.split("/").filter(Boolean)
const firstSegment = segments[0]
const found = VERTICALS.find(v => v.slug === firstSegment)
return found || VERTICALS[0] // Default to Goose
}
const [current, setCurrentState] = useState<Vertical>(getVerticalFromPath)
// Update current when path changes
useEffect(() => {
setCurrentState(getVerticalFromPath())
}, [pathname])
const setCurrent = (slug: VerticalSlug) => {
const found = VERTICALS.find(v => v.slug === slug)
if (found) {
setCurrentState(found)
// Store preference
if (typeof window !== "undefined") {
localStorage.setItem("preferred-vertical", slug)
}
}
}
// Load preference on mount
useEffect(() => {
if (typeof window !== "undefined") {
const stored = localStorage.getItem("preferred-vertical") as VerticalSlug | null
if (stored && VERTICALS.find(v => v.slug === stored)) {
// Only set if not already in a vertical-specific route
const segments = pathname.split("/").filter(Boolean)
const isVerticalRoute = VERTICALS.some(v => v.slug === segments[0])
if (!isVerticalRoute) {
setCurrent(stored)
}
}
}
}, [])
return (
<VerticalContext.Provider value={{ current, setCurrent, all: VERTICALS }}>
{children}
</VerticalContext.Provider>
)
}
export function useVertical() {
const context = useContext(VerticalContext)
if (!context) {
throw new Error("useVertical must be used within a VerticalProvider")
}
return context
}
// Helper to build vertical-aware paths
export function useVerticalPath() {
const { current } = useVertical()
return (path: string) => {
// If path already starts with a vertical, return as-is
const segments = path.split("/").filter(Boolean)
if (VERTICALS.some(v => v.slug === segments[0])) {
return path
}
// Prepend current vertical
return `/${current.slug}${path.startsWith("/") ? path : `/${path}`}`
}
}