Skip to content

Commit 6772259

Browse files
Fix router init for BASE_URL use (#182)
1 parent 6785a4c commit 6772259

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

src/router/Router.svelte

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
import TrainingPage from '../pages/training/TrainingPage.svelte';
1414
import PlaygroundPage from '../pages/PlaygroundPage.svelte';
1515
import { currentPageComponent } from '../views/currentComponentStore';
16-
import { currentPath, navigate, Paths, PathType } from './paths';
16+
import { currentPath, isValidPath, navigate, Paths, PathType } from './paths';
17+
18+
const stripLeadingSlash = (s: string): string => (s.startsWith('/') ? s.slice(1) : s);
1719
1820
function getRoutedComponent(path: PathType) {
1921
switch (path) {
@@ -44,9 +46,7 @@
4446
4547
if (shouldPushState) {
4648
const url =
47-
window.location.origin +
48-
import.meta.env.BASE_URL +
49-
(path.startsWith('/') ? path.slice(1) : path);
49+
window.location.origin + import.meta.env.BASE_URL + stripLeadingSlash(path);
5050
history.pushState({ path: path }, '', url);
5151
}
5252
};
@@ -68,13 +68,10 @@
6868
};
6969
7070
const navigateFromUrl = () => {
71-
let urlPath = window.location.pathname;
72-
if (urlPath.startsWith('/')) {
73-
urlPath = urlPath.substring(1, urlPath.length);
74-
}
75-
let path: PathType = Paths.HOME;
76-
if (Object.values(Paths).includes(urlPath as PathType)) {
77-
path = urlPath as PathType;
71+
const path = stripLeadingSlash(window.location.pathname).slice(
72+
stripLeadingSlash(import.meta.env.BASE_URL).length,
73+
);
74+
if (isValidPath(path)) {
7875
navigate(path);
7976
} else {
8077
history.replaceState({}, '', Paths.HOME);

src/router/paths.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ export const Paths = {
1717

1818
export type PathType = (typeof Paths)[keyof typeof Paths];
1919

20+
export const isValidPath = (s: string): s is PathType => {
21+
return Object.values(Paths).includes(s as PathType);
22+
};
23+
2024
export const currentPathPrivate: Writable<PathType> = writable(Paths.HOME);
2125
export const currentPath = derived(currentPathPrivate, path => path);
2226

0 commit comments

Comments
 (0)