|
| 1 | +import * as React from 'react' |
| 2 | +import { useRouter } from '@tanstack/react-router' |
| 3 | +import { getWidgetsAuthToken } from '@/authkit/serverFunctions' |
| 4 | +import { useToast } from '@/hooks/use-toast' |
| 5 | +import { OrganizationSwitcher, WorkOsWidgets } from '@workos-inc/widgets' |
| 6 | +import { DropdownMenu } from '@radix-ui/themes' |
| 7 | + |
| 8 | +import '@workos-inc/widgets/styles.css' |
| 9 | +import '@radix-ui/themes/styles.css' |
| 10 | + |
| 11 | +type WorkosOrgSwitcherProps = { |
| 12 | + userId: string |
| 13 | + organisationId: string |
| 14 | + label?: string |
| 15 | + redirectTo?: string |
| 16 | + /** |
| 17 | + * If true, wraps the switcher in WorkOsWidgets provider which applies a full-page layout. |
| 18 | + * Leave false for compact embedding in headers/navs to avoid large whitespace. |
| 19 | + */ |
| 20 | + wrapWithProvider?: boolean |
| 21 | + /** |
| 22 | + * When true, injects a default extra group with a Settings item in the switcher dropdown. |
| 23 | + */ |
| 24 | + showSettingsItem?: boolean |
| 25 | +} |
| 26 | + |
| 27 | +export default function WorkosOrgSwitcher({ |
| 28 | + userId, |
| 29 | + organisationId, |
| 30 | + label = 'My Orgs', |
| 31 | + redirectTo = '/dashboard/units', |
| 32 | + wrapWithProvider = false, |
| 33 | + showSettingsItem = false, |
| 34 | +}: WorkosOrgSwitcherProps) { |
| 35 | + const router = useRouter() |
| 36 | + const { toast } = useToast() |
| 37 | + const [authToken, setAuthToken] = React.useState<string | null>(null) |
| 38 | + const [error, setError] = React.useState<string | null>(null) |
| 39 | + const [loading, setLoading] = React.useState(true) |
| 40 | + |
| 41 | + const handleSwitchToOrganization = async (organizationId: string) => { |
| 42 | + try { |
| 43 | + const res = await fetch('/api/auth/workos/switch-org', { |
| 44 | + method: 'POST', |
| 45 | + headers: { 'Content-Type': 'application/json' }, |
| 46 | + body: JSON.stringify({ organizationId, pathname: redirectTo }), |
| 47 | + }) |
| 48 | + const data = await res.json() |
| 49 | + if (!data?.redirectUrl) return |
| 50 | + const url: string = data.redirectUrl |
| 51 | + const isInternal = url.startsWith('/') |
| 52 | + if (isInternal) { |
| 53 | + await router.navigate({ to: url }) |
| 54 | + router.invalidate() |
| 55 | + } else { |
| 56 | + throw new Error('Cannot redirect to external URL') |
| 57 | + } |
| 58 | + } catch (e: any) { |
| 59 | + toast({ |
| 60 | + title: 'Failed to switch organization', |
| 61 | + description: e?.message ?? 'Failed to switch organization', |
| 62 | + variant: 'destructive', |
| 63 | + }) |
| 64 | + console.error('Failed to switch organization', e) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + React.useEffect(() => { |
| 69 | + (async () => { |
| 70 | + try { |
| 71 | + const token = await getWidgetsAuthToken({ data: { userId, organizationId: organisationId } }) |
| 72 | + setAuthToken(token) |
| 73 | + setLoading(false) |
| 74 | + } catch (e: any) { |
| 75 | + setError(e?.message ?? 'Failed to get WorkOS token') |
| 76 | + setLoading(false) |
| 77 | + } |
| 78 | + })() |
| 79 | + }, [userId, organisationId]) |
| 80 | + |
| 81 | + if (loading) return <p>Loading WorkOS…</p> |
| 82 | + if (error) return <p className="text-red-600">Error: {error}</p> |
| 83 | + if (!authToken) return <p>Could not load WorkOS token.</p> |
| 84 | + |
| 85 | + const extraMenu = showSettingsItem ? ( |
| 86 | + <> |
| 87 | + <DropdownMenu.Separator /> |
| 88 | + <DropdownMenu.Group> |
| 89 | + <DropdownMenu.Item onClick={() => router.navigate({ to: '/dashboard/settings/user' })}> |
| 90 | + Settings |
| 91 | + </DropdownMenu.Item> |
| 92 | + </DropdownMenu.Group> |
| 93 | + </> |
| 94 | + ) : null |
| 95 | + |
| 96 | + if (wrapWithProvider) { |
| 97 | + return ( |
| 98 | + <WorkOsWidgets |
| 99 | + // Reset WorkOS full-page layout styles so it fits inside the sidebar |
| 100 | + style={{ minHeight: 'auto', height: 'auto', padding: 0, display: 'contents' } as any} |
| 101 | + > |
| 102 | + <div className="w-full"> |
| 103 | + <OrganizationSwitcher |
| 104 | + authToken={authToken} |
| 105 | + organizationLabel={label} |
| 106 | + switchToOrganization={({ organizationId }) => handleSwitchToOrganization(organizationId)} |
| 107 | + > |
| 108 | + {extraMenu} |
| 109 | + </OrganizationSwitcher> |
| 110 | + </div> |
| 111 | + </WorkOsWidgets> |
| 112 | + ) |
| 113 | + } |
| 114 | + |
| 115 | + return ( |
| 116 | + <OrganizationSwitcher |
| 117 | + authToken={authToken} |
| 118 | + organizationLabel={label} |
| 119 | + switchToOrganization={({ organizationId }) => handleSwitchToOrganization(organizationId)} |
| 120 | + > |
| 121 | + {extraMenu} |
| 122 | + </OrganizationSwitcher> |
| 123 | + ) |
| 124 | +} |
| 125 | + |
| 126 | + |
0 commit comments