Skip to content

Commit

Permalink
fix: pwa router corruption when switching accounts in certain way (#1698
Browse files Browse the repository at this point in the history
)
  • Loading branch information
aeharding authored Dec 27, 2024
1 parent 13637e0 commit e41dec5
Showing 1 changed file with 33 additions and 18 deletions.
51 changes: 33 additions & 18 deletions src/routes/common/ActorRedirect.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Redirect, useLocation, useParams } from "react-router";
import { useLayoutEffect } from "react";
import { useLocation } from "react-router";

import { isInstalled } from "#/helpers/device";
import useIonViewIsVisible from "#/helpers/useIonViewIsVisible";
import { useOptimizedIonRouter } from "#/helpers/useOptimizedIonRouter";
import { useAppSelector } from "#/store";

export const usingActorRedirect = !isInstalled();
Expand All @@ -13,28 +15,41 @@ export default function ActorRedirect({ children }: React.PropsWithChildren) {
}

function ActorRedirectEnabled({ children }: React.PropsWithChildren) {
const { actor } = useParams<{ actor: string }>();
const connectedInstance = useAppSelector(
(state) => state.auth.connectedInstance,
);
const location = useLocation();
const ionViewIsVisible = useIonViewIsVisible();

if (!ionViewIsVisible) return children;
if (!connectedInstance || !actor) return children;
if (connectedInstance === actor) return children;

const [first, second, _wrongActor, ...urlEnd] = location.pathname.split("/");

// no need to redirect if url doesn't have actor
if (!_wrongActor || !isPotentialActor(_wrongActor)) return children;

return (
<Redirect
to={[first, second, connectedInstance, ...urlEnd].join("/")}
push={false}
/>
);
const router = useOptimizedIonRouter();

useLayoutEffect(() => {
if (!ionViewIsVisible) return;

const [first, second, _wrongActor, ...urlEnd] =
location.pathname.split("/");

// no need to redirect if url doesn't have actor
if (!_wrongActor || !isPotentialActor(_wrongActor)) return;

if (!connectedInstance || !_wrongActor) return;
if (connectedInstance === _wrongActor) return;

requestAnimationFrame(() => {
router.push(
[first, second, connectedInstance, ...urlEnd].join("/"),
"root",
"replace",
);
});
}, [
children,
connectedInstance,
ionViewIsVisible,
location.pathname,
router,
]);

return children;
}

function isPotentialActor(host: string) {
Expand Down

0 comments on commit e41dec5

Please sign in to comment.