refactor(webui): extract shared resolveTeamIdFromPath function for root route and component

This commit is contained in:
yiling
2026-06-26 11:18:09 +08:00
parent b6ff60f8b8
commit 6e2e5bdbc2
+23 -17
View File
@@ -20,6 +20,21 @@ import { getLocale, setLocale } from '@/ui/src/paraglide/runtime.js'
import { m } from '@/ui/src/paraglide/messages.js' import { m } from '@/ui/src/paraglide/messages.js'
import { useUserMetadataStore } from '@/ui/stores/user-metadata' import { useUserMetadataStore } from '@/ui/stores/user-metadata'
async function resolveTeamIdFromPath(pathname: string): Promise<string | null> {
const teamIdMatch = pathname.match(/^\/teams\/([^/]+)/)
const teamId = teamIdMatch ? teamIdMatch[1] : null
if (teamId) return teamId
const projectIdMatch = pathname.match(/^\/projects\/([^/]+)/)
const projectId = projectIdMatch ? projectIdMatch[1] : null
if (projectId) {
const { ensureTeamIdForProject } = useTeamContextStore.getState()
return await ensureTeamIdForProject(projectId)
}
return null
}
function RootComponent() { function RootComponent() {
const user = useAuthStore((state) => state.user) const user = useAuthStore((state) => state.user)
const { uploading } = useUploadStore() const { uploading } = useUploadStore()
@@ -32,23 +47,15 @@ function RootComponent() {
return <Outlet /> return <Outlet />
} }
// Extract teamId from pathname if possible const { teamId: storedTeamId, setTeamId } = useTeamContextStore()
// Matches /teams/:teamId
const teamIdMatch = pathname.match(/^\/teams\/([^/]+)/)
const teamId = teamIdMatch ? teamIdMatch[1] : null
const projectIdMatch = pathname.match(/^\/projects\/([^/]+)/)
const projectId = projectIdMatch ? projectIdMatch[1] : null
const { teamId: storedTeamId, setTeamId, ensureTeamIdForProject } = useTeamContextStore()
useEffect(() => { useEffect(() => {
if (teamId) { resolveTeamIdFromPath(pathname).then((resolvedTeamId) => {
setTeamId(teamId) if (resolvedTeamId && resolvedTeamId !== storedTeamId) {
} else if (projectId) { setTeamId(resolvedTeamId)
ensureTeamIdForProject(projectId) }
} })
}, [teamId, projectId, setTeamId, ensureTeamIdForProject]) }, [pathname, storedTeamId, setTeamId])
const { data: me } = useQuery({ const { data: me } = useQuery({
queryKey: ['teams', storedTeamId, 'me'], queryKey: ['teams', storedTeamId, 'me'],
@@ -123,8 +130,7 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({
beforeLoad: async () => { beforeLoad: async () => {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const pathname = window.location.pathname const pathname = window.location.pathname
const teamIdMatch = pathname.match(/^\/teams\/([^/]+)/) const teamId = await resolveTeamIdFromPath(pathname)
const teamId = teamIdMatch ? teamIdMatch[1] : null
if (teamId) { if (teamId) {
const { fetchMetadata, getMetadata } = useUserMetadataStore.getState() const { fetchMetadata, getMetadata } = useUserMetadataStore.getState()