11import { h , createContext , cloneElement } from 'preact' ;
22import { useContext , useMemo , useReducer , useEffect , useLayoutEffect , useRef } from 'preact/hooks' ;
33
4+ let push ;
45const UPDATE = ( state , url ) => {
5- let push = true ;
6+ push = undefined ;
67 if ( url && url . type === 'click' ) {
78 const link = url . target . closest ( 'a[href]' ) ;
89 if ( ! link || link . origin != location . origin || ! / ^ ( _ ? s e l f ) ? $ / i. test ( link . target ) ) return state ;
910
11+ push = true ;
1012 url . preventDefault ( ) ;
1113 url = link . href . replace ( location . origin , '' ) ;
12- } else if ( typeof url !== 'string' ) {
14+ } else if ( typeof url === 'string' ) {
15+ push = true ;
16+ } else {
1317 url = location . pathname + location . search ;
14- push = undefined ;
1518 }
1619
1720 if ( push === true ) history . pushState ( null , '' , url ) ;
@@ -43,12 +46,13 @@ export const exec = (url, route, matches) => {
4346
4447export function LocationProvider ( props ) {
4548 const [ url , route ] = useReducer ( UPDATE , location . pathname + location . search ) ;
49+ const wasPush = push === true ;
4650
4751 const value = useMemo ( ( ) => {
4852 const u = new URL ( url , location . origin ) ;
4953 const path = u . pathname . replace ( / ( .) \/ $ / g, '$1' ) ;
5054 // @ts -ignore-next
51- return { url, path, query : Object . fromEntries ( u . searchParams ) , route } ;
55+ return { url, path, query : Object . fromEntries ( u . searchParams ) , route, wasPush } ;
5256 } , [ url ] ) ;
5357
5458 useEffect ( ( ) => {
@@ -70,7 +74,7 @@ export function Router(props) {
7074
7175 const loc = useLocation ( ) ;
7276
73- const { url, path, query } = loc ;
77+ const { url, path, query, wasPush } = loc ;
7478
7579 const cur = useRef ( loc ) ;
7680 const prev = useRef ( ) ;
@@ -115,6 +119,7 @@ export function Router(props) {
115119 prev . current = prevChildren . current = pending . current = null ;
116120 if ( props . onLoadEnd ) props . onLoadEnd ( url ) ;
117121 update ( 0 ) ;
122+ if ( wasPush ) scrollTo ( 0 , 0 ) ;
118123 } ;
119124
120125 if ( p ) {
0 commit comments