1
1
import { type ReactNode , useEffect , useMemo , useState } from "react"
2
- import { useRouter } from "next/router "
2
+ import { useSearchParams } from "next/navigation "
3
3
4
4
import { trackCustomEvent } from "@/lib/utils/matomo"
5
5
@@ -18,9 +18,9 @@ import { Phone } from "./Phone"
18
18
import { SimulatorModal } from "./SimulatorModal"
19
19
import { Template } from "./Template"
20
20
import type { PathId , SimulatorData } from "./types"
21
- import { getValidPathId } from "./utils"
21
+ import { getValidPathId , isValidPathId } from "./utils"
22
22
23
- import { usePathname } from "@/i18n/routing"
23
+ import { usePathname , useRouter } from "@/i18n/routing"
24
24
25
25
type SimulatorProps = {
26
26
children : ReactNode
@@ -29,21 +29,21 @@ type SimulatorProps = {
29
29
export const Simulator = ( { children, data } : SimulatorProps ) => {
30
30
const router = useRouter ( )
31
31
const pathname = usePathname ( )
32
+ const searchParams = useSearchParams ( )
32
33
33
34
// Track step
34
35
const [ step , setStep ] = useState ( 0 ) // 0-indexed to use as array index
35
36
36
37
// Track pathID
37
- const pathId = getValidPathId ( router . query . sim as string )
38
+ const pathId = getValidPathId ( searchParams . get ( PATH_ID_QUERY_PARAM ) )
38
39
const simulator : SimulatorDetails | null = pathId ? data [ pathId ] : null
39
40
const totalSteps : number = simulator ? simulator . explanations . length : 0
40
41
41
42
// If pathId present, modal is open, else closed
42
43
const isOpen = ! ! pathId
43
44
44
45
const clearUrlParams = ( ) => {
45
- const pathWithoutParams = pathname . replace ( / \? [ ^ # ] * / , "" )
46
- router . replace ( pathWithoutParams )
46
+ router . replace ( pathname , { scroll : false } )
47
47
}
48
48
49
49
// When simulator closed: log event, clear URL params and close modal
@@ -62,7 +62,9 @@ export const Simulator = ({ children, data }: SimulatorProps) => {
62
62
// Remove URL search param if invalid pathId
63
63
useEffect ( ( ) => {
64
64
setStep ( 0 )
65
- if ( ! pathId ) clearUrlParams ( )
65
+ if ( pathId && ! isValidPathId ( pathId ) ) {
66
+ clearUrlParams ( )
67
+ }
66
68
// eslint-disable-next-line react-hooks/exhaustive-deps
67
69
} , [ pathId ] )
68
70
@@ -91,10 +93,15 @@ export const Simulator = ({ children, data }: SimulatorProps) => {
91
93
92
94
const openPath = ( id : PathId ) : void => {
93
95
// Set new pathId in navigation
94
- const params = new URLSearchParams ( )
95
- params . set ( PATH_ID_QUERY_PARAM , id )
96
- const url = `?${ params . toString ( ) } #${ SIMULATOR_ID } `
97
- router . replace ( url )
96
+ router . replace (
97
+ {
98
+ pathname,
99
+ query : {
100
+ [ PATH_ID_QUERY_PARAM ] : id ,
101
+ } ,
102
+ } ,
103
+ { scroll : false }
104
+ )
98
105
}
99
106
100
107
// Navigation object passed to child components
0 commit comments