@@ -6,12 +6,28 @@ import { joinPath } from '@/lib/paths';
6
6
import { useCurrentPagePath } from '../hooks' ;
7
7
import { DropdownMenuItem } from './DropdownMenu' ;
8
8
9
- function useVariantSpaceHref ( variantSpaceUrl : string ) {
9
+ interface VariantSpace {
10
+ id : Space [ 'id' ] ;
11
+ title : Space [ 'title' ] ;
12
+ url : string ;
13
+ }
14
+
15
+ // When switching to a different variant space, we reconstruct the URL by swapping the space path.
16
+ function useVariantSpaceHref ( variantSpaceUrl : string , currentSpacePath : string , active = false ) {
10
17
const currentPathname = useCurrentPagePath ( ) ;
11
18
19
+ // We need to ensure that the variant space URL is not the same as the current space path.
20
+ // If it is, we return only the variant space URL to redirect to the root of the variant space.
21
+ // This is necessary in case the currentPathname is the same as the variantSpaceUrl,
22
+ // otherwise we would redirect to the same space if the variant space that we are switching to is the default one.
23
+ if ( ! active && currentPathname . startsWith ( `${ currentSpacePath } /` ) ) {
24
+ return variantSpaceUrl ;
25
+ }
26
+
12
27
if ( URL . canParse ( variantSpaceUrl ) ) {
13
28
const targetUrl = new URL ( variantSpaceUrl ) ;
14
29
targetUrl . pathname = joinPath ( targetUrl . pathname , currentPathname ) ;
30
+
15
31
targetUrl . searchParams . set ( 'fallback' , 'true' ) ;
16
32
17
33
return targetUrl . toString ( ) ;
@@ -22,15 +38,36 @@ function useVariantSpaceHref(variantSpaceUrl: string) {
22
38
}
23
39
24
40
export function SpacesDropdownMenuItem ( props : {
25
- variantSpace : { id : Space [ 'id' ] ; title : Space [ 'title' ] ; url : string } ;
41
+ variantSpace : VariantSpace ;
26
42
active : boolean ;
43
+ currentSpacePath : string ;
27
44
} ) {
28
- const { variantSpace, active } = props ;
29
- const variantHref = useVariantSpaceHref ( variantSpace . url ) ;
45
+ const { variantSpace, active, currentSpacePath } = props ;
46
+ const variantHref = useVariantSpaceHref ( variantSpace . url , currentSpacePath , active ) ;
30
47
31
48
return (
32
49
< DropdownMenuItem key = { variantSpace . id } href = { variantHref } active = { active } >
33
50
{ variantSpace . title }
34
51
</ DropdownMenuItem >
35
52
) ;
36
53
}
54
+
55
+ export function SpacesDropdownMenuItems ( props : {
56
+ slimSpaces : VariantSpace [ ] ;
57
+ curPath : string ;
58
+ } ) {
59
+ const { slimSpaces, curPath } = props ;
60
+
61
+ return (
62
+ < >
63
+ { slimSpaces . map ( ( space ) => (
64
+ < SpacesDropdownMenuItem
65
+ key = { space . id }
66
+ variantSpace = { space }
67
+ active = { false }
68
+ currentSpacePath = { curPath }
69
+ />
70
+ ) ) }
71
+ </ >
72
+ ) ;
73
+ }
0 commit comments