2023-07-26 17:54:03 +03:00
|
|
|
import { UUID } from "crypto";
|
|
|
|
import { redirect, useParams, usePathname } from "next/navigation";
|
2023-07-24 15:17:21 +03:00
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
|
|
|
|
import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";
|
|
|
|
import { useDevice } from "@/lib/hooks/useDevice";
|
|
|
|
|
|
|
|
import { sortBrainsByName } from "../utils/sortByName";
|
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
|
|
export const useBrainsList = () => {
|
|
|
|
const { isMobile } = useDevice();
|
|
|
|
const [open, setOpen] = useState(!isMobile);
|
|
|
|
const [searchQuery, setSearchQuery] = useState("");
|
|
|
|
const { allBrains } = useBrainContext();
|
2023-07-26 17:54:03 +03:00
|
|
|
const { currentBrainId } = useBrainContext();
|
|
|
|
const params = useParams();
|
|
|
|
|
|
|
|
const brainId = params?.brainId as UUID | undefined;
|
2023-07-24 15:17:21 +03:00
|
|
|
|
|
|
|
const pathname = usePathname();
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setOpen(!isMobile);
|
|
|
|
}, [isMobile, pathname]);
|
|
|
|
|
|
|
|
const brains = allBrains.filter((brain) => {
|
|
|
|
const query = searchQuery.toLowerCase();
|
|
|
|
const name = brain.name.toLowerCase();
|
|
|
|
|
|
|
|
return name.includes(query);
|
|
|
|
});
|
|
|
|
|
2023-07-26 17:54:03 +03:00
|
|
|
useEffect(() => {
|
|
|
|
if (brainId !== undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-09-21 10:35:53 +03:00
|
|
|
if (
|
|
|
|
currentBrainId !== null &&
|
|
|
|
pathname !== null &&
|
|
|
|
!pathname.includes("library")
|
|
|
|
) {
|
2023-07-26 17:54:03 +03:00
|
|
|
redirect(`/brains-management/${currentBrainId}`);
|
|
|
|
}
|
2023-09-21 10:35:53 +03:00
|
|
|
}, [brainId, currentBrainId, pathname]);
|
2023-07-26 17:54:03 +03:00
|
|
|
|
2023-07-24 15:17:21 +03:00
|
|
|
return {
|
|
|
|
open,
|
|
|
|
setOpen,
|
|
|
|
searchQuery,
|
|
|
|
setSearchQuery,
|
|
|
|
brains: sortBrainsByName(brains),
|
|
|
|
};
|
|
|
|
};
|