import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter, RouterProvider } from "@tanstack/react-router";
import React, { useEffect } from "react";
import ReactDOM from "react-dom/client";
// Import the generated route tree
import { routeTree } from "./routeTree.gen";
import {
clearPersistedQueryCache,
persistQueryCache,
restoreQueryCache,
} from "./utils/queryCachePersistence";
import { delUser } from "./utils/storage/user";
import { ApiProvider, initializeApi, useApiInContext } from "./utils/store/api";
import { CentralProvider, useCentralStore } from "./utils/store/central";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
networkMode: "always",
},
mutations: {
networkMode: "always",
},
},
});
//TODO: Need help implementing modal routes in TanStack Router
// const SearchMask = createRouteMask({
// routeTree,
// from: "/searchModal,
// to: "/search",
// params: true,
// });
// Create a new router instance
const router = createRouter({
routeTree,
context: {
api: undefined!,
createApi: undefined!,
user: undefined,
jellyfinSDK: undefined!,
fetchCurrentUser: undefined!,
queryClient,
},
// Preload route chunks/data when the user shows intent (hover/focus), so
// navigation itself stays instant without paying for every route at boot.
defaultPreload: "intent",
defaultPreloadStaleTime: 30_000,
// Only animate real page changes; search-param updates (typing in the
// search field) must not trigger a transition on every keystroke.
defaultViewTransition: {
types: ({ pathChanged }) =>
pathChanged && document.visibilityState === "visible" ? ["page"] : false,
},
scrollRestoration: true,
scrollRestorationBehavior: "auto",
});
// Register the router instance for type safety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
function ProviderWrapper() {
const [api, createApi, jellyfinSDK] = useApiInContext((s) => [
s.api,
s.createApi,
s.jellyfin,
]);
const [user, fetchCurrentUser] = useCentralStore((s) => [
s.currentUser,
s.fetchCurrentUser,
]);
// Validate/refresh the saved session in the background. The UI reads the
// minimal user snapshot from disk immediately, so this never blocks paint.
useEffect(() => {
if (!api?.accessToken) return;
fetchCurrentUser(api).catch(async (error) => {
console.error("Could not restore the saved session", error);
const status = (error as { response?: { status?: number } })?.response
?.status;
// Only an actual authorization failure should log the user out.
if (status !== 401 && status !== 403) return;
await delUser();
queryClient.clear();
clearPersistedQueryCache();
createApi(api.basePath, undefined);
router.navigate({
to: "/login/manual",
search: { redirect: window.location.pathname },
});
});
}, [api?.accessToken, fetchCurrentUser, createApi]);
useEffect(() => {
router.invalidate(); // This is a hack to force the router to re-evaluate the routes and re-run the beforeLoad functions
}, [api?.accessToken]);
return (
);
}
const init = async () => {
performance.mark("blink:init-start");
// Frameless titlebar: macOS keeps the native traffic lights; Windows and
// Linux use the custom window buttons in the header.
const userAgent = navigator.userAgent;
const isAndroid = userAgent.includes("Android");
const isIOS = /iPhone|iPad|iPod/.test(userAgent);
if (isAndroid) {
document.documentElement.classList.add("is-android", "is-mobile");
} else if (isIOS) {
document.documentElement.classList.add("is-ios", "is-mobile");
} else if (userAgent.includes("Macintosh")) {
document.documentElement.classList.add("is-macos");
} else if (userAgent.includes("Windows")) {
document.documentElement.classList.add("is-windows");
} else {
document.documentElement.classList.add("is-linux");
}
// The overlay scrollbar hides the native page scrollbar. Apply it before the
// first render so layout measurements do not see a ~13px scrollbar that is
// removed a frame later (which made library cards resize after load).
document.documentElement.classList.add("has-overlay-scrollbar");
document.body.classList.add("has-overlay-scrollbar");
// Layout transitions during a live window resize cause visible wobble
// (headers, cards, MUI components). Disable them until resizing settles.
let resizeTimer: ReturnType | undefined;
window.addEventListener("resize", () => {
document.documentElement.classList.add("is-resizing");
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
document.documentElement.classList.remove("is-resizing");
}, 200);
});
const { api: initialApi, user: initialUser } = await initializeApi();
performance.mark("blink:session-restored");
const owner =
initialApi?.basePath && initialUser?.Id
? `${initialApi.basePath}|${initialUser.Id}`
: undefined;
if (owner) {
restoreQueryCache(queryClient, owner);
persistQueryCache(queryClient, () => owner);
}
ReactDOM.createRoot(document.getElementById("root")!).render(
,
);
performance.mark("blink:react-render");
};
init();