Skip to content

Commit 48da30c

Browse files
committed
fix: hash routing bug when no hash at start page
1 parent 72bf5b6 commit 48da30c

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/router/router.ts

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ export class MobxRouter implements IMobxRouter {
3333
config.location ?? new MobxLocation(this.history, config.abortSignal);
3434
this.queryParams =
3535
config.queryParams ?? new QueryParams(this.location, this.history);
36+
37+
if (!this.location.hash && this.type === 'hash') {
38+
this.hashNavigate('/');
39+
}
3640
}
3741

3842
createPath(to: RouterToConfig): RouterPath {
@@ -71,7 +75,51 @@ export class MobxRouter implements IMobxRouter {
7175
].join('');
7276
}
7377

74-
private lastViewTransition?: ViewTransition;
78+
protected hashNavigate(to: RouterToConfig, options?: RouterNavigateParams) {
79+
const path = this.createPath(to);
80+
const url = this.createUrl(path, this.type);
81+
const state = options?.state ?? null;
82+
83+
this.wrapInViewTransition(() => {
84+
this.location.hash = path.hash;
85+
this.history.replaceState(state, '', url);
86+
});
87+
}
88+
89+
protected browserNavigate(
90+
to: RouterToConfig,
91+
options?: RouterNavigateParams,
92+
) {
93+
const path = this.createPath(to);
94+
const url = this.createUrl(path, this.type);
95+
const state = options?.state ?? null;
96+
97+
this.wrapInViewTransition(() => {
98+
if (options?.replace) {
99+
this.history.replaceState(state, '', url);
100+
} else {
101+
this.history.pushState(state, '', url);
102+
}
103+
});
104+
}
105+
106+
protected lastViewTransition?: ViewTransition;
107+
108+
protected wrapInViewTransition(action: () => void) {
109+
if (this.config.useStartViewTransition && document.startViewTransition) {
110+
if (this.lastViewTransition) {
111+
this.lastViewTransition.skipTransition();
112+
}
113+
this.lastViewTransition = document.startViewTransition(() => {
114+
startTransition(action);
115+
});
116+
this.lastViewTransition.finished.finally(() => {
117+
delete this.lastViewTransition;
118+
});
119+
} else {
120+
action();
121+
}
122+
}
75123

76124
navigate(to: RouterToConfig, options?: RouterNavigateParams): void {
77125
const path = this.createPath(to);

0 commit comments

Comments
 (0)