feat: rewrite router to avoid CSS selector conflicts

Implement custom event system and safe navigation functions.

#VERCEL_SKIP

Co-authored-by: Allan K. Koech <44490960+allankoechke@users.noreply.github.com>
This commit is contained in:
v0
2025-06-26 18:08:03 +00:00
parent 529f5345ef
commit cb5c035895
4 changed files with 194 additions and 84 deletions

View File

@@ -14,34 +14,51 @@ export default function Page() {
React.useEffect(() => {
setMounted(true)
const savedToken = localStorage.getItem("admin_token")
if (savedToken) {
setToken(savedToken)
// Get saved token safely
try {
const savedToken = localStorage.getItem("admin_token")
if (savedToken) {
setToken(savedToken)
}
} catch (error) {
console.warn("Failed to get saved token:", error)
}
}, [])
React.useEffect(() => {
if (mounted) {
// Prevent hash from being used as CSS selector
const currentPath = route.path
try {
const currentPath = route.path
if (!token && currentPath !== "/login") {
navigate("/login")
} else if (token && currentPath === "/login") {
navigate("/tables")
if (!token && currentPath !== "/login") {
navigate("/login")
} else if (token && currentPath === "/login") {
navigate("/tables")
}
} catch (error) {
console.warn("Failed to handle route change:", error)
}
}
}, [token, route.path, mounted, navigate])
const handleLogin = (newToken: string) => {
setToken(newToken)
navigate("/tables")
try {
setToken(newToken)
navigate("/tables")
} catch (error) {
console.warn("Failed to handle login:", error)
}
}
const handleLogout = () => {
setToken(null)
localStorage.removeItem("admin_token")
navigate("/login")
try {
setToken(null)
localStorage.removeItem("admin_token")
navigate("/login")
} catch (error) {
console.warn("Failed to handle logout:", error)
}
}
if (!mounted) {

View File

@@ -51,22 +51,30 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
const showError = React.useCallback(
(error: string, type: "error" | "warning" = "error") => {
// Prevent error loops by checking if error is already being shown
if (error.includes("Unauthorized") || error.includes("auth")) {
return // Don't show toast for auth errors, handle with dialog
}
try {
// Prevent error loops by checking if error is already being shown
if (error.includes("Unauthorized") || error.includes("auth")) {
return // Don't show toast for auth errors, handle with dialog
}
toast({
variant: type === "error" ? "destructive" : "default",
title: type === "error" ? "Error" : "Warning",
description: error,
})
toast({
variant: type === "error" ? "destructive" : "default",
title: type === "error" ? "Error" : "Warning",
description: error,
})
} catch (toastError) {
console.warn("Failed to show error toast:", toastError)
}
},
[toast],
)
const handleUnauthorized = React.useCallback(() => {
setAuthErrorDialog(true)
try {
setAuthErrorDialog(true)
} catch (error) {
console.warn("Failed to handle unauthorized:", error)
}
}, [])
const apiClient = React.useMemo(
@@ -99,13 +107,21 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
}
const handleLogout = () => {
localStorage.removeItem("admin_token")
onLogout()
try {
localStorage.removeItem("admin_token")
onLogout()
} catch (error) {
console.warn("Failed to logout:", error)
}
}
const handleAuthErrorLogin = () => {
setAuthErrorDialog(false)
handleLogout()
try {
setAuthErrorDialog(false)
handleLogout()
} catch (error) {
console.warn("Failed to handle auth error login:", error)
}
}
const sidebarItems = [
@@ -183,7 +199,13 @@ export function AdminDashboard({ token, onLogout }: AdminDashboardProps) {
{sidebarItems.map((item) => (
<SidebarMenuItem key={item.id}>
<SidebarMenuButton
onClick={() => navigate(item.path)}
onClick={() => {
try {
navigate(item.path)
} catch (error) {
console.warn("Failed to navigate:", error)
}
}}
isActive={currentSection === item.id}
className={currentSection === item.id ? "bg-accent text-accent-foreground" : ""}
>

View File

@@ -54,7 +54,11 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
}
const handleTableClick = (tableName: string) => {
navigate(`/tables/${tableName}`)
try {
navigate(`/tables/${tableName}`)
} catch (error) {
console.warn("Failed to navigate to table:", error)
}
}
const handleRefresh = async () => {
@@ -75,7 +79,13 @@ export function DatabaseSection({ apiClient, tables, onTablesUpdate }: DatabaseS
return (
<TableDetailView
table={tableInfo}
onBack={() => navigate("/tables")}
onBack={() => {
try {
navigate("/tables")
} catch (error) {
console.warn("Failed to navigate back:", error)
}
}}
apiClient={apiClient}
onTableUpdate={(updatedTable) => {
const updatedTables = tables.map((t) => (t.id === updatedTable.id ? updatedTable : t))

View File

@@ -11,100 +11,161 @@ export interface ParsedRoute {
params: RouteParams
}
// Use a custom event system instead of relying on hash changes
const ROUTE_CHANGE_EVENT = "custom-route-change"
let currentRoute: ParsedRoute = { path: "/tables", params: {} }
export function parseRoute(hash: string): ParsedRoute {
// Remove the # if present
const cleanHash = hash.startsWith("#") ? hash.slice(1) : hash
try {
// Remove the # if present
const cleanHash = hash.startsWith("#") ? hash.slice(1) : hash
// If empty, default to /tables
if (!cleanHash) {
return { path: "/tables", params: {} }
}
// Split path and query string
const [pathPart, queryPart] = cleanHash.split("?")
// Parse query parameters
const params: RouteParams = {}
if (queryPart) {
try {
const searchParams = new URLSearchParams(queryPart)
for (const [key, value] of searchParams.entries()) {
params[key] = value
}
} catch (error) {
console.warn("Failed to parse query parameters:", error)
// If empty, default to /tables
if (!cleanHash) {
return { path: "/tables", params: {} }
}
}
return {
path: pathPart || "/tables",
params,
// Split path and query string
const [pathPart, queryPart] = cleanHash.split("?")
// Parse query parameters
const params: RouteParams = {}
if (queryPart) {
try {
const searchParams = new URLSearchParams(queryPart)
for (const [key, value] of searchParams.entries()) {
params[key] = value
}
} catch (error) {
console.warn("Failed to parse query parameters:", error)
}
}
return {
path: pathPart || "/tables",
params,
}
} catch (error) {
console.warn("Failed to parse route:", error)
return { path: "/tables", params: {} }
}
}
export function buildRoute(path: string, params?: RouteParams): string {
let route = path.startsWith("/") ? path : `/${path}`
try {
let route = path.startsWith("/") ? path : `/${path}`
if (params && Object.keys(params).length > 0) {
const searchParams = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value) {
searchParams.set(key, value)
if (params && Object.keys(params).length > 0) {
const searchParams = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value) {
searchParams.set(key, value)
}
}
const queryString = searchParams.toString()
if (queryString) {
route += `?${queryString}`
}
}
const queryString = searchParams.toString()
if (queryString) {
route += `?${queryString}`
}
}
return `#${route}`
return route
} catch (error) {
console.warn("Failed to build route:", error)
return "/tables"
}
}
// Custom event dispatcher
function dispatchRouteChange(route: ParsedRoute) {
const event = new CustomEvent(ROUTE_CHANGE_EVENT, { detail: route })
window.dispatchEvent(event)
}
export function useRouter() {
const [route, setRoute] = React.useState<ParsedRoute>(() => {
if (typeof window !== "undefined") {
return parseRoute(window.location.hash)
try {
const initialRoute = parseRoute(window.location.hash)
currentRoute = initialRoute
return initialRoute
} catch (error) {
console.warn("Failed to get initial route:", error)
return { path: "/tables", params: {} }
}
}
return { path: "/tables", params: {} }
})
const updateRoute = React.useCallback(() => {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
}, [])
React.useEffect(() => {
// Set initial route
updateRoute()
const handleCustomRouteChange = (event: CustomEvent) => {
try {
const newRoute = event.detail as ParsedRoute
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle route change:", error)
}
}
// Listen for hash changes
const handleHashChange = () => {
updateRoute()
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle hash change:", error)
}
}
// Listen for popstate (back/forward buttons)
const handlePopState = () => {
updateRoute()
try {
const newRoute = parseRoute(window.location.hash)
setRoute(newRoute)
currentRoute = newRoute
} catch (error) {
console.warn("Failed to handle pop state:", error)
}
}
// Listen for our custom events
window.addEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
// Still listen for hash changes for browser navigation
window.addEventListener("hashchange", handleHashChange)
window.addEventListener("popstate", handlePopState)
return () => {
window.removeEventListener(ROUTE_CHANGE_EVENT, handleCustomRouteChange as EventListener)
window.removeEventListener("hashchange", handleHashChange)
window.removeEventListener("popstate", handlePopState)
}
}, [updateRoute])
}, [])
const navigate = React.useCallback((path: string, params?: RouteParams) => {
const newRoute = buildRoute(path, params)
try {
const routePath = buildRoute(path, params)
const newRoute: ParsedRoute = { path: routePath, params: params || {} }
// Prevent the hash from being used as a CSS selector by updating location properly
if (window.location.hash !== newRoute) {
window.location.hash = newRoute
// Update URL without triggering hash change event
const hashValue = `#${routePath}`
// Use replaceState to avoid adding to history if it's the same route
if (window.location.hash !== hashValue) {
window.history.pushState(null, "", hashValue)
}
// Dispatch our custom event
dispatchRouteChange(newRoute)
} catch (error) {
console.warn("Failed to navigate:", error)
}
}, [])
return { route, navigate }
}
// Helper function to get current route without hooks
export function getCurrentRoute(): ParsedRoute {
return currentRoute
}