feat: add infinite scroll & fix some ui
This commit is contained in:
+7
-15
@@ -1,9 +1,8 @@
|
||||
import { useWAClient } from "./context";
|
||||
import Avatar from "@/components/ui/avatar";
|
||||
import { useChats } from "@/hooks/useChats";
|
||||
import { useContacts } from "@/hooks/useContact";
|
||||
import { getFormattedName, getId } from "@/lib/utils";
|
||||
import { getFormattedName } from "@/lib/utils";
|
||||
import type { ChatDTO, ContactDTO } from "@shared/dto";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
FaceGrinningIcon,
|
||||
@@ -17,21 +16,14 @@ import {
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
type Props = {
|
||||
selected: ChatDTO | null;
|
||||
onSelect: (chat: ChatDTO) => void;
|
||||
selected: string | null;
|
||||
onSelect: (chat: string) => void;
|
||||
};
|
||||
export default function ChatsSection({ selected, onSelect }: Props) {
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const { client, isReady } = useWAClient();
|
||||
const contacts = useContacts();
|
||||
const { data: chats } = useQuery({
|
||||
queryKey: ["chats"],
|
||||
queryFn: () =>
|
||||
client
|
||||
.listChats({ limit: 500 })
|
||||
.then((res) => res.map((i) => ({ ...i, id: getId(i.id) }))),
|
||||
enabled: isReady,
|
||||
const { data: chats } = useChats({
|
||||
refetchInterval: 10_000,
|
||||
});
|
||||
|
||||
@@ -88,8 +80,8 @@ export default function ChatsSection({ selected, onSelect }: Props) {
|
||||
{filteredChats?.map((chat) => (
|
||||
<button
|
||||
key={chat.id}
|
||||
onClick={() => onSelect(chat)}
|
||||
className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition cursor-pointer ${selected?.id === chat.id ? "bg-accent" : "hover:bg-muted/70"}`}
|
||||
onClick={() => onSelect(chat.id)}
|
||||
className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition cursor-pointer ${selected === chat.id ? "bg-accent" : "hover:bg-muted/70"}`}
|
||||
>
|
||||
<Avatar
|
||||
name={chat.formattedTitle || chat.name}
|
||||
|
||||
+104
-40
@@ -1,55 +1,97 @@
|
||||
import { useWAClient } from "./context";
|
||||
import { getFormattedName, getId } from "@/lib/utils";
|
||||
import type { ChatDTO } from "@shared/dto";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { cn } from "cn";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
CheckCheckIcon,
|
||||
CheckIcon,
|
||||
Loader2Icon,
|
||||
PaperclipIcon,
|
||||
PhoneCallIcon,
|
||||
SendIcon,
|
||||
} from "lucide-react";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import MessageMedia from "@/components/message-media";
|
||||
import Avatar from "@/components/ui/avatar";
|
||||
import { useContacts } from "@/hooks/useContact";
|
||||
import { useMessageEvent } from "@/hooks/useMessageEvent";
|
||||
import { useHashRouter } from "@/hooks/useHashRouter";
|
||||
import { useChats } from "@/hooks/useChats";
|
||||
import Avatar from "@/components/ui/avatar";
|
||||
import { useIntersection } from "@/hooks/useIntersection";
|
||||
import Paragraph from "@/components/paragraph";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
type Props = {
|
||||
chat: ChatDTO;
|
||||
mobileChat: boolean;
|
||||
setMobileChat: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
chatId: string | null;
|
||||
maxCount?: number;
|
||||
};
|
||||
|
||||
export default function MessagesSection({
|
||||
chat,
|
||||
mobileChat,
|
||||
setMobileChat,
|
||||
}: Props) {
|
||||
export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||
const { client, isReady } = useWAClient();
|
||||
const router = useHashRouter();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setPending] = useState(false);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: chats } = useChats();
|
||||
const { data: contacts } = useContacts();
|
||||
|
||||
const chatId = getId(chat.id);
|
||||
const { data: messages, refetch } = useQuery({
|
||||
const {
|
||||
data: messages,
|
||||
isLoading,
|
||||
refetch,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ["messages", chatId],
|
||||
queryFn: () => client.getMessages({ chatId, count: 50 }),
|
||||
queryFn: ({ pageParam }) =>
|
||||
client
|
||||
.getMessages({
|
||||
chatId: chatId!,
|
||||
count: maxCount,
|
||||
direction: "before",
|
||||
id: pageParam,
|
||||
})
|
||||
.then((i) => i.reverse()),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
enabled: Boolean(chatId && isReady),
|
||||
refetchInterval: 10_1000,
|
||||
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length < maxCount) return undefined;
|
||||
return getId(lastPage[lastPage.length - 1]?.id);
|
||||
},
|
||||
select: (data) => data.pages.flat(),
|
||||
});
|
||||
|
||||
useMessageEvent((data) => {
|
||||
if (data.chatId === chatId) refetch();
|
||||
if (data.chatId !== chatId) return;
|
||||
|
||||
queryClient.setQueryData(["messages", chatId], (old: any) => {
|
||||
if (!old) return old;
|
||||
|
||||
return {
|
||||
...old,
|
||||
pages: [[data, ...old.pages[0]], ...old.pages.slice(1)],
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const endScrollRef = useIntersection(() => {
|
||||
if (hasNextPage && !isFetchingNextPage && !isLoading) {
|
||||
fetchNextPage();
|
||||
}
|
||||
});
|
||||
|
||||
const chat = useMemo(
|
||||
() => chats?.find((c) => c.id === chatId),
|
||||
[chats, chatId],
|
||||
);
|
||||
|
||||
const messageList = useMemo(() => {
|
||||
return messages
|
||||
?.filter((i) => !["revoked"].includes(i.type as never))
|
||||
@@ -76,13 +118,12 @@ export default function MessagesSection({
|
||||
from,
|
||||
quotedMsg,
|
||||
};
|
||||
})
|
||||
?.reverse();
|
||||
});
|
||||
}, [messages, contacts]);
|
||||
|
||||
async function sendMessage() {
|
||||
const text = message.trim();
|
||||
if (!text) return;
|
||||
if (!text || !chatId) return;
|
||||
|
||||
try {
|
||||
setPending(true);
|
||||
@@ -98,23 +139,26 @@ export default function MessagesSection({
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`flex min-w-0 flex-1 flex-col bg-muted ${mobileChat ? "flex" : "hidden md:flex"}`}
|
||||
className={`flex min-w-0 flex-1 flex-col bg-muted ${chatId ? "flex" : "hidden md:flex"}`}
|
||||
>
|
||||
<header className="flex items-center justify-between border-b border-border bg-card px-4 py-3 sm:px-6">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<button
|
||||
aria-label="Back to conversations"
|
||||
onClick={() => setMobileChat(false)}
|
||||
className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-muted md:hidden cursor-pointer"
|
||||
onClick={() => router.goBack()}
|
||||
className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-muted md:hidden cursor-pointer -ml-2"
|
||||
>
|
||||
<ArrowLeftIcon size={19} />
|
||||
</button>
|
||||
|
||||
<Avatar name={chat.formattedTitle || chat.name} className="size-10" />
|
||||
<Avatar
|
||||
name={chat?.formattedTitle || chat?.name}
|
||||
className="size-10"
|
||||
/>
|
||||
|
||||
<div className="min-w-0">
|
||||
<h2 className="truncate text-sm font-semibold">
|
||||
{chat.formattedTitle || chat.name}
|
||||
{chat?.formattedTitle || chat?.name}
|
||||
</h2>
|
||||
|
||||
{/* <p className="text-xs text-[#1ea66a]">
|
||||
@@ -153,7 +197,7 @@ export default function MessagesSection({
|
||||
|
||||
{messageList?.map((item, index) => (
|
||||
<div
|
||||
id={item.id}
|
||||
id={item.id.replace(/^(?:false_|true_)/, "")}
|
||||
key={`${item.timestamp}-${index}`}
|
||||
className={`mb-3 flex ${item.fromMe ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
@@ -178,13 +222,14 @@ export default function MessagesSection({
|
||||
["chat", "image", "document"].includes(
|
||||
item.quotedMsg.type as string,
|
||||
) ? (
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
const el = document.getElementById(
|
||||
getId(item.quotedMsgId),
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const id = getId(item.quotedMsgId).replace(
|
||||
/^(?:false_|true_)/,
|
||||
"",
|
||||
);
|
||||
const el = document.getElementById(id);
|
||||
if (el) {
|
||||
el.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
@@ -197,14 +242,17 @@ export default function MessagesSection({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{getFormattedName(item.quotedMsg.from)}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap wrap-break-word">
|
||||
{item.quotedMsg.filename ||
|
||||
|
||||
<Paragraph
|
||||
text={
|
||||
item.quotedMsg.filename ||
|
||||
item.quotedMsg.caption ||
|
||||
(item.quotedMsg.type === "chat"
|
||||
? item.quotedMsg.body
|
||||
: "Quoted")}
|
||||
</p>
|
||||
</a>
|
||||
: "Quoted")
|
||||
}
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{item.type === "image" ||
|
||||
@@ -215,9 +263,7 @@ export default function MessagesSection({
|
||||
) : null}
|
||||
|
||||
{item.type === "chat" || item.caption ? (
|
||||
<p className="whitespace-pre-wrap wrap-break-word">
|
||||
{item.caption || item.body}
|
||||
</p>
|
||||
<Paragraph text={item.caption || item.body} />
|
||||
) : null}
|
||||
|
||||
{item.type === "call_log" && (
|
||||
@@ -249,6 +295,24 @@ export default function MessagesSection({
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div ref={endScrollRef} className="h-1" />
|
||||
|
||||
<div className="mb-6 flex items-center justify-center gap-2 text-[11px] text-muted-foreground">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<div className="flex items-center gap-2">
|
||||
{isLoading ||
|
||||
(isFetchingNextPage && (
|
||||
<Loader2Icon className="animate-spin size-4" />
|
||||
))}
|
||||
<span>
|
||||
{isLoading || isFetchingNextPage
|
||||
? "Loading..."
|
||||
: "End of messages"}
|
||||
</span>
|
||||
</div>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border bg-card px-3 py-3 sm:px-6 sm:py-4">
|
||||
|
||||
+8
-23
@@ -1,25 +1,19 @@
|
||||
import ChatsSection from "./chats";
|
||||
import type { ChatDTO } from "@shared/dto";
|
||||
import MessagesSection from "./messages";
|
||||
import DevicesSection from "./devices";
|
||||
import { useLocalStorage } from "@/hooks/useLocalStorage";
|
||||
import { useHashRouter } from "@/hooks/useHashRouter";
|
||||
import MessagesSection from "./messages";
|
||||
|
||||
export default function Page() {
|
||||
const [chat, setChat] = useLocalStorage<ChatDTO | null>(
|
||||
"app/current-chat",
|
||||
null,
|
||||
);
|
||||
const [mobileChat, setMobileChat] = useLocalStorage<boolean>(
|
||||
"app/mobile-chat",
|
||||
false,
|
||||
);
|
||||
const router = useHashRouter();
|
||||
const [curDeviceId, setDeviceId] = useLocalStorage<string>("app/device", "");
|
||||
const chatId = router.query.get("chatId");
|
||||
|
||||
return (
|
||||
<main className="bg-background text-foreground flex overflow-hidden h-screen max-h-dvh">
|
||||
{/* <div className="mx-auto flex h-dvh max-w-360 overflow-hidden bg-card shadow-xl sm:h-[calc(100dvh-2rem)] sm:rounded-2xl lg:h-[calc(100dvh-3rem)]"> */}
|
||||
<aside
|
||||
className={`flex w-full shrink-0 flex-col border-r border-border bg-card md:w-85 lg:w-1/3 max-w-md ${mobileChat ? "hidden md:flex" : "flex"}`}
|
||||
className={`flex w-full shrink-0 flex-col border-r border-border bg-card md:w-85 lg:w-1/3 max-w-md ${chatId ? "hidden md:flex" : "flex"}`}
|
||||
>
|
||||
{/* <header className="flex items-center justify-between border-b border-border px-5 py-5">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -50,11 +44,8 @@ export default function Page() {
|
||||
</header> */}
|
||||
|
||||
<ChatsSection
|
||||
selected={chat}
|
||||
onSelect={(c) => {
|
||||
setChat(c);
|
||||
setMobileChat(true);
|
||||
}}
|
||||
selected={chatId}
|
||||
onSelect={(id) => router.push(`/?chatId=${id}`)}
|
||||
/>
|
||||
|
||||
{/* <div className="border-t border-border px-5 py-4">
|
||||
@@ -80,13 +71,7 @@ export default function Page() {
|
||||
<DevicesSection curDeviceId={curDeviceId} setDeviceId={setDeviceId} />
|
||||
</aside>
|
||||
|
||||
{chat ? (
|
||||
<MessagesSection
|
||||
chat={chat}
|
||||
mobileChat={mobileChat}
|
||||
setMobileChat={setMobileChat}
|
||||
/>
|
||||
) : null}
|
||||
{chatId ? <MessagesSection chatId={chatId} /> : null}
|
||||
{/* </div> */}
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useWAClient } from "@/app/context";
|
||||
import { storage } from "@/lib/storage";
|
||||
import type { MessageDTO } from "@shared/dto";
|
||||
import { cn } from "cn";
|
||||
import { DownloadIcon, Loader2Icon, PaperclipIcon } from "lucide-react";
|
||||
import {
|
||||
DownloadIcon,
|
||||
ImageIcon,
|
||||
Loader2Icon,
|
||||
PaperclipIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
type Props = {
|
||||
@@ -17,7 +22,9 @@ export default function MessageMedia({ data }: Props) {
|
||||
const [isLoading, setLoading] = useState(false);
|
||||
const [isDownloaded, setDownloaded] = useState(false);
|
||||
const [body, setBody] = useState(
|
||||
type === "image" ? "data:image/webp;base64," + data.body : data.body,
|
||||
type === "image" && data.body
|
||||
? "data:image/webp;base64," + data.body
|
||||
: data.body,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -85,17 +92,28 @@ export default function MessageMedia({ data }: Props) {
|
||||
return (
|
||||
<a
|
||||
href="#"
|
||||
onClick={() => openMedia()}
|
||||
className="w-full h-32 aspect-video block relative overflow-hidden"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
openMedia();
|
||||
}}
|
||||
className={cn(
|
||||
"w-full min-h-32 max-h-40 aspect-video block relative overflow-hidden rounded",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={body || ""}
|
||||
alt=""
|
||||
className={cn(
|
||||
"w-full h-full object-cover",
|
||||
!isDownloaded && "blur-sm",
|
||||
)}
|
||||
/>
|
||||
{body ? (
|
||||
<img
|
||||
src={body}
|
||||
alt=""
|
||||
className={cn(
|
||||
"w-full h-full object-cover",
|
||||
!isDownloaded && "blur-[2px]",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 bg-black/30 flex items-center justify-center">
|
||||
<ImageIcon className="size-8 opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && (
|
||||
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { cn } from "cn";
|
||||
import React from "react";
|
||||
|
||||
type Token =
|
||||
| { type: "text"; value: string }
|
||||
| { type: "bold"; value: string }
|
||||
| { type: "italic"; value: string }
|
||||
| { type: "strike"; value: string }
|
||||
| { type: "code"; value: string }
|
||||
| { type: "url"; value: string };
|
||||
|
||||
function renderWhatsAppMessage(message: string): React.ReactNode {
|
||||
const regex =
|
||||
/(\*[^*\n]+\*|_[^_\n]+_|~[^~\n]+~|`[^`\n]+`|https?:\/\/[^\s<]+|www\.[^\s<]+)/g;
|
||||
|
||||
const tokens: Token[] = [];
|
||||
let lastIndex = 0;
|
||||
|
||||
for (const match of message.matchAll(regex)) {
|
||||
const index = match.index ?? 0;
|
||||
const value = match[0];
|
||||
|
||||
if (index > lastIndex) {
|
||||
tokens.push({
|
||||
type: "text",
|
||||
value: message.slice(lastIndex, index),
|
||||
});
|
||||
}
|
||||
|
||||
if (value.startsWith("*")) {
|
||||
tokens.push({ type: "bold", value: value.slice(1, -1) });
|
||||
} else if (value.startsWith("_")) {
|
||||
tokens.push({ type: "italic", value: value.slice(1, -1) });
|
||||
} else if (value.startsWith("~")) {
|
||||
tokens.push({ type: "strike", value: value.slice(1, -1) });
|
||||
} else if (value.startsWith("`")) {
|
||||
tokens.push({ type: "code", value: value.slice(1, -1) });
|
||||
} else {
|
||||
// Remove punctuation that commonly follows a URL.
|
||||
const url = value.replace(/[.,!?;:)]+$/, "");
|
||||
|
||||
tokens.push({ type: "url", value: url });
|
||||
|
||||
// Preserve trailing punctuation.
|
||||
if (url.length < value.length) {
|
||||
tokens.push({
|
||||
type: "text",
|
||||
value: value.slice(url.length),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
lastIndex = index + value.length;
|
||||
}
|
||||
|
||||
if (lastIndex < message.length) {
|
||||
tokens.push({
|
||||
type: "text",
|
||||
value: message.slice(lastIndex),
|
||||
});
|
||||
}
|
||||
|
||||
return tokens.map((token, i) => {
|
||||
switch (token.type) {
|
||||
case "bold":
|
||||
return (
|
||||
<strong key={i} className="font-bold">
|
||||
{token.value}
|
||||
</strong>
|
||||
);
|
||||
|
||||
case "italic":
|
||||
return (
|
||||
<em key={i} className="italic">
|
||||
{token.value}
|
||||
</em>
|
||||
);
|
||||
|
||||
case "strike":
|
||||
return (
|
||||
<del key={i} className="line-through">
|
||||
{token.value}
|
||||
</del>
|
||||
);
|
||||
|
||||
case "code":
|
||||
return (
|
||||
<code
|
||||
key={i}
|
||||
className="rounded bg-black/10 px-1 py-0.5 font-mono text-sm"
|
||||
>
|
||||
{token.value}
|
||||
</code>
|
||||
);
|
||||
|
||||
case "url":
|
||||
return (
|
||||
<a
|
||||
key={i}
|
||||
href={
|
||||
token.value.startsWith("www.")
|
||||
? `https://${token.value}`
|
||||
: token.value
|
||||
}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="break-all text-blue-200 underline hover:text-blue-300"
|
||||
>
|
||||
{token.value}
|
||||
</a>
|
||||
);
|
||||
|
||||
case "text":
|
||||
return <React.Fragment key={i}>{token.value}</React.Fragment>;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type Props = {
|
||||
text?: string | null;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function Paragraph({ text, className }: Props) {
|
||||
if (!text) return null;
|
||||
|
||||
return (
|
||||
<div className={cn("whitespace-pre-wrap wrap-break-word", className)}>
|
||||
{renderWhatsAppMessage(text)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useWAClient } from "@/app/context";
|
||||
import { getId } from "@/lib/utils";
|
||||
import type { WhatsAppClient } from "@client/whatsapp";
|
||||
import { useQuery, type UseQueryOptions } from "@tanstack/react-query";
|
||||
|
||||
async function getChats(client: WhatsAppClient) {
|
||||
return client
|
||||
.listChats({ limit: 500 })
|
||||
.then((res) => res.map((i) => ({ ...i, id: getId(i.id) })));
|
||||
}
|
||||
|
||||
type Response = Awaited<ReturnType<typeof getChats>>;
|
||||
|
||||
export function useChats(opt?: Partial<UseQueryOptions>) {
|
||||
const { client, isReady } = useWAClient();
|
||||
return useQuery<Response, Error>({
|
||||
queryKey: ["chats"],
|
||||
queryFn: () => getChats(client),
|
||||
enabled: isReady,
|
||||
...((opt || {}) as any),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
type HashLocation = {
|
||||
path: string;
|
||||
query: URLSearchParams;
|
||||
search: string;
|
||||
};
|
||||
|
||||
type HashRouter = HashLocation & {
|
||||
navigate: (path: string, options?: NavigateOptions) => void;
|
||||
push: (path: string) => void;
|
||||
reset: (path?: string) => void;
|
||||
canGoback: () => boolean;
|
||||
goBack: () => void;
|
||||
};
|
||||
|
||||
type NavigateOptions = {
|
||||
replace?: boolean;
|
||||
};
|
||||
|
||||
function getHashLocation(): HashLocation {
|
||||
const hash = window.location.hash.slice(1);
|
||||
|
||||
const [pathname, search = ""] = hash.split("?");
|
||||
|
||||
const path = pathname
|
||||
? pathname.startsWith("/")
|
||||
? pathname
|
||||
: `/${pathname}`
|
||||
: "/";
|
||||
|
||||
return {
|
||||
path,
|
||||
search: search ? `?${search}` : "",
|
||||
query: new URLSearchParams(search),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePath(path: string) {
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
function setHashPath(path: string, replace = false) {
|
||||
const normalized = normalizePath(path);
|
||||
const hash = `#${normalized}`;
|
||||
|
||||
if (replace) {
|
||||
window.history.replaceState(null, "", hash);
|
||||
|
||||
// replaceState doesn't emit hashchange
|
||||
window.dispatchEvent(new HashChangeEvent("hashchange"));
|
||||
} else {
|
||||
window.location.hash = normalized;
|
||||
}
|
||||
}
|
||||
|
||||
export function useHashRouter(): HashRouter {
|
||||
const [location, setLocation] = useState<HashLocation>(getHashLocation);
|
||||
|
||||
useEffect(() => {
|
||||
const handleChange = () => {
|
||||
setLocation(getHashLocation());
|
||||
};
|
||||
|
||||
window.addEventListener("hashchange", handleChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("hashchange", handleChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const navigate = useCallback(
|
||||
(path: string, options: NavigateOptions = {}) => {
|
||||
setHashPath(path, options.replace);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const push = useCallback(
|
||||
(path: string) => {
|
||||
navigate(path);
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
const reset = useCallback(
|
||||
(path = "/") => {
|
||||
navigate(path, { replace: true });
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
const canGoback = useCallback(() => window.history.length > 1, []);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
if (canGoback()) {
|
||||
window.history.back();
|
||||
} else {
|
||||
reset();
|
||||
}
|
||||
}, [canGoback, reset]);
|
||||
|
||||
return {
|
||||
...location,
|
||||
navigate,
|
||||
push,
|
||||
reset,
|
||||
canGoback,
|
||||
goBack,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function useIntersection(
|
||||
callback: (entry: IntersectionObserverEntry) => void,
|
||||
options: any = {},
|
||||
) {
|
||||
const ref = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const element = ref.current;
|
||||
if (!element) return;
|
||||
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
callback(entry);
|
||||
}
|
||||
}, options);
|
||||
|
||||
observer.observe(element);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [callback, options]);
|
||||
|
||||
return ref;
|
||||
}
|
||||
Reference in New Issue
Block a user