refactor: move most routing logic to tanstack

This commit is contained in:
Prayag Prajapati committed 2024-05-29 18:10:22 +05:30
1 parent b8552ac35d
commit c22dbefeea
22 files changed
+1191 -1502

No files matched your search

+2 -10
View File
@@ -93,7 +93,6 @@ export const AppBar = () => {
const navigate = useNavigate();
const [display, setDisplay] = useState(false);
const [backButtonVisible, setBackButtonVisible] = useState(false);
const location = useLocation();
@@ -133,8 +132,6 @@ export const AppBar = () => {
const queryClient = useQueryClient();
const [tabValue] = useSettingsStore((state) => [state.tabValue]);
const handleLogout = async () => {
console.log("Logging out user...");
await api.logout();
@@ -160,11 +157,6 @@ export const AppBar = () => {
setDisplay(true);
}
if (location.pathname === "/home") {
setBackButtonVisible(false);
} else {
setBackButtonVisible(true);
}
}, [location]);
const [showDrawer, setShowDrawer] = useState(false);
@@ -207,10 +199,10 @@ export const AppBar = () => {
</div>
<div className="flex flex-row" style={{ gap: "0.6em" }}>
<IconButton onClick={() => navigate("/search")}>
<IconButton onClick={() => navigate({ to: "/search" })}>
<div className="material-symbols-rounded">search</div>
</IconButton>
<IconButton onClick={() => navigate("/favorite")}>
<IconButton onClick={() => navigate({ to: "/favorite" })}>
<div className="material-symbols-rounded">favorite</div>
</IconButton>
<IconButton sx={{ p: 0 }} onClick={handleMenuOpen}>
@@ -1,3 +1,4 @@
import { useApiInContext } from "@/utils/store/api";
import { playItemFromQueue } from "@/utils/store/playback";
import useQueue from "@/utils/store/queue";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
+1
View File
@@ -13,6 +13,7 @@ import { getTypeIcon } from "../utils/iconsCollection";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
import { useMutation, useQuery } from "@tanstack/react-query";
import "./queueButton.scss";
import { useApiInContext } from "@/utils/store/api";
import { useRouteContext } from "@tanstack/react-router";
const QueueButton = () => {
const api = useApiInContext((s) => s.api);
+26 -8
View File
@@ -64,14 +64,32 @@ export const Card = ({
const api = useApiInContext((s) => s.api);
const navigate = useNavigate();
const defaultOnClick = () => {
if (availableSpecialRoutes.includes(item.Type)) {
navigate({ to: `/${item.Type.toLocaleLowerCase()}/${item.Id}` });
} else if (!!item.Role || item.Type === BaseItemKind.Person) {
navigate({ to: `/person/${item.Id}` });
} else if (item.Type === BaseItemKind.MusicArtist) {
navigate({ to: `/artist/${item.Id}` });
} else {
navigate({ to: `/item/${item.Id}` });
switch (item.Type) {
case BaseItemKind.BoxSet:
navigate({ to: "/boxset/$id", params: { id: item.Id } });
break;
case BaseItemKind.Episode:
navigate({ to: "/episode/$id", params: { id: item.Id } });
break;
case BaseItemKind.MusicAlbum:
navigate({ to: "/album/$id", params: { id: item.Id } });
break;
case BaseItemKind.MusicArtist:
navigate({ to: "/artist/$id", params: { id: item.Id } });
break;
case BaseItemKind.Person:
navigate({ to: "/person/$id", params: { id: item.Id } });
break;
case BaseItemKind.Series:
navigate({ to: "/series/$id", params: { id: item.Id } });
break;
case BaseItemKind.Playlist:
navigate({ to: "/playlist/$id", params: { id: item.Id } });
break;
default:
navigate({ to: "/item/$id", params: { id: item.Id } });
break;
}
};
@@ -17,10 +17,11 @@ import PlayButton from "../../buttons/playButton";
import TrackList from "../tracksList/index";
import "./albumArtist.scss";
import { useApiInContext } from "@/utils/store/api";
import { Link, useRouteContext } from "@tanstack/react-router";
export const ArtistAlbum = ({ user, album, boxProps }) => {
const api = useRouteContext({ from: "/" }).api;
const api = useApiInContext((s) => s.api);
const albumTracks = useQuery({
queryKey: ["artist", "album", album.Id],
queryFn: async () => {
@@ -56,16 +56,18 @@ export const LatestMediaSection = ({ latestMediaLib }) => {
imageType={"Primary"}
cardCaption={
item.Type === BaseItemKind.Episode
? `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`
? `S${item.ParentIndexNumber ?? 0}:E${
item.IndexNumber ?? 0
} - ${item.Name ?? "Unknown"}`
: item.Type === BaseItemKind.Series
? `${item.ProductionYear} - ${
? `${item.ProductionYear} - ${
item.EndDate
? new Date(item.EndDate).toLocaleString([], {
year: "numeric",
})
})
: "Present"
}`
: item.ProductionYear
}`
: item.ProductionYear
}
cardType={
item.Type === BaseItemKind.MusicAlbum ||
+5 -4
View File
@@ -8,6 +8,7 @@ import { getRuntimeMusic } from "../../../utils/date/time";
import { useAudioPlayback } from "../../../utils/store/audioPlayback";
import LikeButton from "../../buttons/likeButton";
import "./tracksList.scss";
import { useApiInContext } from "@/utils/store/api";
import { useRouteContext } from "@tanstack/react-router";
export default function TracksList({
@@ -15,7 +16,7 @@ export default function TracksList({
user,
queryKey,
}: { tracks: BaseItemDto[]; user: UserDto; queryKey: [] }) {
const api = useRouteContext({ from: "/" }).api;
const api = useApiInContext((s) => s.api);
const [
currentItem,
@@ -58,11 +59,11 @@ export default function TracksList({
</div>
{tracks.map((track, index) => (
<div
className={currentItem.Id === track.Id ? "track playing" : "track"}
className={currentItem?.Id === track.Id ? "track playing" : "track"}
key={track.Id}
onClick={() => playTrack(index)}
>
{currentItem.Id === track.Id ? (
{currentItem?.Id === track.Id ? (
<span className="material-symbols-rounded ">equalizer</span>
) : (
<Typography>{track.IndexNumber ?? "-"}</Typography>
@@ -81,7 +82,7 @@ export default function TracksList({
>
{track.Name}
</Typography>
<Typography>{getRuntimeMusic(track.RunTimeTicks)}</Typography>
<Typography>{getRuntimeMusic(track?.RunTimeTicks)}</Typography>
</div>
))}
</div>
+3 -2
View File
@@ -6,6 +6,7 @@ import LikeButton from "../buttons/likeButton";
import PlayButton from "../buttons/playButton";
import TextLink from "../textLink";
import "./musicTrack.scss";
import { useApiInContext } from "@/utils/store/api";
import { useRouteContext } from "@tanstack/react-router";
/**
@@ -33,7 +34,7 @@ const MusicTrack = ({
trackIndex,
className = "",
}) => {
const api = useRouteContext({ from: "/" }).api;
const api = useApiInContext((s) => s.api);
const [currentTrackItem] = useAudioPlayback((state) => [state.item]);
return (
@@ -87,7 +88,7 @@ const MusicTrack = ({
variant="subtitle1"
style={{
color:
item.Id === currentTrackItem.Id ? "hsl(337, 96%, 56%)" : "white",
item.Id === currentTrackItem?.Id ? "hsl(337, 96%, 56%)" : "white",
}}
>
{item.Name}
+10 -5
View File
@@ -432,10 +432,13 @@ const Settings = () => {
<Typography variant="subtitle2">Client Version:</Typography>
<Chip
icon={
<span className="material-symbols-rounded">
<span
className="material-symbols-rounded"
style={{ "--wght": 500 }}
>
{updateInfo.data?.shouldUpdate
? "update"
: "update_disabled"}
? "new_release"
: "new_releases"}
</span>
}
label={
@@ -443,7 +446,9 @@ const Settings = () => {
{applicationVersion}
</Typography>
}
color={updateInfo.data?.shouldUpdate ? "error" : "info"}
color={
updateInfo.data?.shouldUpdate ? "error" : "success"
}
size="small"
style={{
width: "fit-content !important",
@@ -461,7 +466,7 @@ const Settings = () => {
<Chip
icon={
<span className="material-symbols-rounded">
update
new_releases
</span>
}
label={
+129 -10
View File
@@ -264,36 +264,36 @@ declare module '@tanstack/react-router' {
}
'/_api/favorite/': {
id: '/_api/favorite/'
path: '/favorite/'
fullPath: '/favorite/'
path: '/favorite'
fullPath: '/favorite'
preLoaderRoute: typeof ApiFavoriteIndexImport
parentRoute: typeof ApiImport
}
'/_api/home/': {
id: '/_api/home/'
path: '/home/'
fullPath: '/home/'
path: '/home'
fullPath: '/home'
preLoaderRoute: typeof ApiHomeIndexImport
parentRoute: typeof ApiImport
}
'/_api/login/': {
id: '/_api/login/'
path: '/login/'
fullPath: '/login/'
path: '/login'
fullPath: '/login'
preLoaderRoute: typeof ApiLoginIndexImport
parentRoute: typeof ApiImport
}
'/_api/player/': {
id: '/_api/player/'
path: '/player/'
fullPath: '/player/'
path: '/player'
fullPath: '/player'
preLoaderRoute: typeof ApiPlayerIndexImport
parentRoute: typeof ApiImport
}
'/_api/search/': {
id: '/_api/search/'
path: '/search/'
fullPath: '/search/'
path: '/search'
fullPath: '/search'
preLoaderRoute: typeof ApiSearchIndexImport
parentRoute: typeof ApiImport
}
@@ -336,3 +336,122 @@ export const routeTree = rootRoute.addChildren({
})
/* prettier-ignore-end */
/* ROUTE_MANIFEST_START
{
"routes": {
"__root__": {
"filePath": "__root.tsx",
"children": [
"/",
"/_api",
"/setup/server/add",
"/setup/server/error",
"/setup/server/list"
]
},
"/": {
"filePath": "index.tsx"
},
"/_api": {
"filePath": "_api.tsx",
"children": [
"/_api/album/$id",
"/_api/artist/$id",
"/_api/boxset/$id",
"/_api/episode/$id",
"/_api/item/$id",
"/_api/library/$id",
"/_api/login/list",
"/_api/login/manual",
"/_api/person/$id",
"/_api/playlist/$id",
"/_api/series/$id",
"/_api/favorite/",
"/_api/home/",
"/_api/login/",
"/_api/player/",
"/_api/search/",
"/_api/login/$userId/$userName"
]
},
"/_api/album/$id": {
"filePath": "_api/album/$id.tsx",
"parent": "/_api"
},
"/_api/artist/$id": {
"filePath": "_api/artist/$id.tsx",
"parent": "/_api"
},
"/_api/boxset/$id": {
"filePath": "_api/boxset/$id.tsx",
"parent": "/_api"
},
"/_api/episode/$id": {
"filePath": "_api/episode/$id.tsx",
"parent": "/_api"
},
"/_api/item/$id": {
"filePath": "_api/item/$id.tsx",
"parent": "/_api"
},
"/_api/library/$id": {
"filePath": "_api/library/$id.tsx",
"parent": "/_api"
},
"/_api/login/list": {
"filePath": "_api/login/list.tsx",
"parent": "/_api"
},
"/_api/login/manual": {
"filePath": "_api/login/manual.tsx",
"parent": "/_api"
},
"/_api/person/$id": {
"filePath": "_api/person/$id.tsx",
"parent": "/_api"
},
"/_api/playlist/$id": {
"filePath": "_api/playlist/$id.jsx",
"parent": "/_api"
},
"/_api/series/$id": {
"filePath": "_api/series/$id.tsx",
"parent": "/_api"
},
"/setup/server/add": {
"filePath": "setup/server.add.tsx"
},
"/setup/server/error": {
"filePath": "setup/server.error.tsx"
},
"/setup/server/list": {
"filePath": "setup/server.list.tsx"
},
"/_api/favorite/": {
"filePath": "_api/favorite/index.tsx",
"parent": "/_api"
},
"/_api/home/": {
"filePath": "_api/home/index.tsx",
"parent": "/_api"
},
"/_api/login/": {
"filePath": "_api/login/index.tsx",
"parent": "/_api"
},
"/_api/player/": {
"filePath": "_api/player/index.tsx",
"parent": "/_api"
},
"/_api/search/": {
"filePath": "_api/search/index.jsx",
"parent": "/_api"
},
"/_api/login/$userId/$userName": {
"filePath": "_api/login/$userId.$userName.tsx",
"parent": "/_api"
}
}
}
ROUTE_MANIFEST_END */
+3
View File
@@ -22,6 +22,7 @@ import {
import { useIsFetching, useIsMutating } from "@tanstack/react-query";
import {
Outlet,
ScrollRestoration,
createRootRoute,
createRootRouteWithContext,
useNavigate,
@@ -64,6 +65,7 @@ export const Route = createRootRouteWithContext<ApiContext>()({
console.error(error.error);
},
component: () => {
"use memo";
const isQueryFetching = useIsFetching();
const isMutating = useIsMutating();
const routeIsLoading = useRouterState().isLoading;
@@ -107,6 +109,7 @@ export const Route = createRootRouteWithContext<ApiContext>()({
<ThemeProvider theme={theme}>
<SnackbarProvider maxSnack={5}>
<CssBaseline />
<ScrollRestoration />
<Settings />
<EasterEgg />
<NProgress
+13 -12
View File
@@ -29,22 +29,23 @@ export const Route = createFileRoute("/_api")({
try {
await getSystemApi(context.api).getPingSystem(); // Verify server status
} catch (error) {
console.error(error);
throw redirect({
to: "/setup/server/error",
search: {
redirect: location.href,
},
});
}
try {
await getUserApi(context.api).getCurrentUser(); // Verify user is able to authenticate
} catch (error) {
throw redirect({
to: "/login/manual",
search: {
redirect: location.href,
},
});
if (context.api.accessToken) {
try {
await getUserApi(context.api).getCurrentUser(); // Verify user is able to authenticate
} catch (error) {
console.error(error);
throw redirect({
to: "/login/manual",
search: {
redirect: location.href,
},
});
}
}
}
},
+7 -4
View File
@@ -38,7 +38,7 @@ import { useBackdropStore } from "@/utils/store/backdrop";
import "./album.scss";
import IconLink from "@/components/iconLink";
import { createFileRoute } from "@tanstack/react-router";
import { Link, createFileRoute } from "@tanstack/react-router";
function TabPanel(props) {
const { children, value, index, ...other } = props;
@@ -387,10 +387,13 @@ function MusicAlbumTitlePage() {
</Typography>
<div className="item-detail-cast-grid">
{item.data.ArtistItems.map((artist) => (
<NavLink
<Link
className="item-detail-cast-card"
key={artist.Id}
to={`/artist/${artist.Id}`}
to="/artist/$id"
params={{
id: artist.Id,
}}
>
<div
style={{
@@ -430,7 +433,7 @@ function MusicAlbumTitlePage() {
{artist.Role}
</Typography>
</div>
</NavLink>
</Link>
))}
</div>
</div>
+1 -1
View File
@@ -36,7 +36,7 @@ export const Route = createFileRoute("/_api/home/")({
});
function Home() {
const api = Route.useRouteContext().api;
const api = useApiInContext((s) => s.api);
const user = useQuery({
queryKey: ["user"],
+1
View File
@@ -97,6 +97,7 @@ export const Route = createFileRoute("/_api/item/$id")({
});
function ItemDetail() {
"use memo";
const { id } = Route.useParams();
const api = Route.useRouteContext().api;
+6 -1
View File
@@ -965,7 +965,12 @@ function SeriesTitlePage() {
return (
<motion.div
key={episode.Id}
onClick={() => navigate(`/episode/${episode.Id}`)}
onClick={() =>
navigate({
to: "/episode/$id",
params: { id: episode.Id },
})
}
initial={{
transform: "translateY(10px)",
opacity: 0,
+16
View File
@@ -0,0 +1,16 @@
.server-error {
&-container {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 1em;
.material-symbols-rounded {
font-size: 10em;
// --wght: 500;
// --opsz: 40
}
}
}
+31 -2
View File
@@ -1,6 +1,35 @@
import { createFileRoute } from "@tanstack/react-router";
import { Link, createFileRoute, useNavigate } from "@tanstack/react-router";
import React from "react";
import "./server.error.scss";
import { Button, ButtonGroup, Typography } from "@mui/material";
import { relaunch } from "@tauri-apps/api/process";
export const Route = createFileRoute("/setup/server/error")({
component: () => <div>Hello /setup/server/error!</div>,
component: () => {
const navigate = useNavigate();
return (
<div className="scrollY server-error-container">
<span className="material-symbols-rounded fill gradient-text">
report
</span>
<Typography variant="h4">Unable to connect to server!</Typography>
<div className="flex flex-align-center" style={{ gap: "1em" }}>
<Button
variant="contained"
onClick={() => navigate({ to: "/setup/server/list" })}
>
Change Server
</Button>
<Button
variant="contained"
color="secondary"
onClick={async () => await relaunch()}
>
Restart Blink
</Button>
</div>
</div>
);
},
});