(feat): add replys
(feat): move to SenderId (feat): other chat improvements
This commit is contained in:
parent
95a79892c6
commit
e0843a11a6
9 changed files with 6138 additions and 3234 deletions
|
|
@ -1,17 +1,21 @@
|
||||||
import Input from "@tensamin/markdown/input";
|
import Input from "@tensamin/markdown/input";
|
||||||
import {
|
import {
|
||||||
|
Avatar,
|
||||||
|
AvatarFallback,
|
||||||
|
AvatarImage,
|
||||||
Card,
|
Card,
|
||||||
CardHeader,
|
CardHeader,
|
||||||
Popover,
|
Popover,
|
||||||
PopoverContent,
|
PopoverContent,
|
||||||
PopoverTrigger,
|
PopoverTrigger,
|
||||||
|
Skeleton,
|
||||||
} from "@tensamin/ui";
|
} from "@tensamin/ui";
|
||||||
import { useStorage } from "@tensamin/storage/context";
|
import { useStorage } from "@tensamin/storage/context";
|
||||||
import * as React from "react";
|
import React, { useEffect, useState, useRef } from "react";
|
||||||
import { Button } from "@tensamin/ui";
|
import { Button } from "@tensamin/ui";
|
||||||
|
|
||||||
import { Plus, Laugh, FileVideo } from "lucide-react";
|
import { Plus, Laugh, FileVideo, Forward, X } from "lucide-react";
|
||||||
import { useChat } from "../context";
|
import { useChat, useReplyMessage } from "../context";
|
||||||
import { useMTP } from "@tensamin/mtp";
|
import { useMTP } from "@tensamin/mtp";
|
||||||
import { log, toast } from "@tensamin/shared/log";
|
import { log, toast } from "@tensamin/shared/log";
|
||||||
import { cn, useIsMobile } from "@tensamin/ui";
|
import { cn, useIsMobile } from "@tensamin/ui";
|
||||||
|
|
@ -19,6 +23,8 @@ import { encryptChatText } from "@tensamin/crypto/chatSecret";
|
||||||
|
|
||||||
import { useSession } from "@tensamin/storage/session";
|
import { useSession } from "@tensamin/storage/session";
|
||||||
import GifPicker from "./gifPicker";
|
import GifPicker from "./gifPicker";
|
||||||
|
import Wrapper from "@tensamin/user/wrapper";
|
||||||
|
import Text from "@tensamin/markdown/text";
|
||||||
|
|
||||||
export default function InputComponent({
|
export default function InputComponent({
|
||||||
value,
|
value,
|
||||||
|
|
@ -27,26 +33,33 @@ export default function InputComponent({
|
||||||
value: string;
|
value: string;
|
||||||
setValue: (value: string) => void;
|
setValue: (value: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const [invertEnterBehavior, setInvertEnterBehavior] = React.useState(false);
|
const [invertEnterBehavior, setInvertEnterBehavior] = useState(false);
|
||||||
|
|
||||||
const { send } = useMTP();
|
const { send } = useMTP();
|
||||||
const { addLiveMessage, chatSecret, userId, inputBoxRef } = useChat();
|
const {
|
||||||
|
addLiveMessage,
|
||||||
|
chatSecret,
|
||||||
|
userId,
|
||||||
|
inputBoxRef,
|
||||||
|
replyTo,
|
||||||
|
setReplyTo,
|
||||||
|
} = useChat();
|
||||||
const { load, save } = useStorage();
|
const { load, save } = useStorage();
|
||||||
const { moveUserIdToTop } = useSession();
|
const { moveUserIdToTop } = useSession();
|
||||||
const gifPopoverRef = React.useRef<HTMLDivElement>(null);
|
const gifPopoverRef = useRef<HTMLDivElement>(null);
|
||||||
const [gifPopoverOpen, setGifPopoverOpen] = React.useState(false);
|
const [gifPopoverOpen, setGifPopoverOpen] = useState(false);
|
||||||
const [gifPopoverSize, setGifPopoverSize] = React.useState<{
|
const [gifPopoverSize, setGifPopoverSize] = useState<{
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
React.useEffect(() => {
|
useEffect(() => {
|
||||||
void load("settings.reverse_enter_behavior").then((shouldInvert) => {
|
void load("settings.reverse_enter_behavior").then((shouldInvert) => {
|
||||||
setInvertEnterBehavior(shouldInvert);
|
setInvertEnterBehavior(shouldInvert);
|
||||||
});
|
});
|
||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
useEffect(() => {
|
||||||
void load("chat_picker_size").then((size) => {
|
void load("chat_picker_size").then((size) => {
|
||||||
if (size) {
|
if (size) {
|
||||||
setGifPopoverSize(size);
|
setGifPopoverSize(size);
|
||||||
|
|
@ -57,7 +70,7 @@ export default function InputComponent({
|
||||||
async function handleSubmit(content = value, preserveContent = false) {
|
async function handleSubmit(content = value, preserveContent = false) {
|
||||||
if (content.trim() === "") return;
|
if (content.trim() === "") return;
|
||||||
|
|
||||||
const time = Date.now();
|
const time = new Date().getTime();
|
||||||
const currentValue = content;
|
const currentValue = content;
|
||||||
|
|
||||||
if (!Number.isSafeInteger(userId) || userId <= 0) {
|
if (!Number.isSafeInteger(userId) || userId <= 0) {
|
||||||
|
|
@ -76,18 +89,20 @@ export default function InputComponent({
|
||||||
NotEncrypted: true,
|
NotEncrypted: true,
|
||||||
SendTime: time,
|
SendTime: time,
|
||||||
Content: currentValue,
|
Content: currentValue,
|
||||||
SentBySelf: true,
|
SenderId: ownId,
|
||||||
MessageState: "awaiting",
|
MessageState: "awaiting",
|
||||||
|
...(replyTo && { ReplyId: replyTo }),
|
||||||
});
|
});
|
||||||
|
|
||||||
log(3, "chat", "purple", "Live message added, encrypting...");
|
log(3, "chat", "purple", "Live message added, encrypting...");
|
||||||
|
|
||||||
const encryptedContent = await encryptChatText(chatSecret, currentValue).catch(
|
const encryptedContent = await encryptChatText(
|
||||||
(err) => {
|
chatSecret,
|
||||||
|
currentValue,
|
||||||
|
).catch((err) => {
|
||||||
toast("error", "Failed to encrypt message", String(err));
|
toast("error", "Failed to encrypt message", String(err));
|
||||||
reference.setFailed(true);
|
reference.setFailed(true);
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
if (!encryptedContent) return;
|
if (!encryptedContent) return;
|
||||||
|
|
||||||
|
|
@ -106,6 +121,10 @@ export default function InputComponent({
|
||||||
toast("error", "Failed to send message");
|
toast("error", "Failed to send message");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (replyTo) {
|
||||||
|
setReplyTo(undefined);
|
||||||
|
}
|
||||||
|
|
||||||
log(3, "chat", "purple", "Message sent");
|
log(3, "chat", "purple", "Message sent");
|
||||||
|
|
||||||
moveUserIdToTop(userId);
|
moveUserIdToTop(userId);
|
||||||
|
|
@ -168,7 +187,59 @@ export default function InputComponent({
|
||||||
window.addEventListener("pointerup", handlePointerUp);
|
window.addEventListener("pointerup", handlePointerUp);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { ownId, replyMessage, replyUserId } = useReplyMessage();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div className="flex flex-col">
|
||||||
|
{replyTo !== undefined && (
|
||||||
|
<div className="self-center rounded-t-lg bg-background border-t border-x flex items-center justify-start w-[90%] p-1">
|
||||||
|
<div className="flex gap-1 w-full items-center">
|
||||||
|
<Forward
|
||||||
|
color="var(--muted-foreground)"
|
||||||
|
className="opacity-60"
|
||||||
|
size={18}
|
||||||
|
/>
|
||||||
|
{replyMessage ? (
|
||||||
|
<>
|
||||||
|
<Wrapper
|
||||||
|
userId={replyUserId ?? ownId}
|
||||||
|
loading={<Skeleton className="rounded-full" />}
|
||||||
|
component={(user) => (
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src={user.Avatar} />
|
||||||
|
<AvatarFallback>
|
||||||
|
{user.Display.slice(2, 0).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="max-w-full max-h-5 h-5 text-xs truncate">
|
||||||
|
<Text value={replyMessage.Content} />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Skeleton className="w-5 h-5 aspect-square rounded-full" />
|
||||||
|
<Skeleton className="w-full h-5" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setReplyTo(undefined);
|
||||||
|
}}
|
||||||
|
className="w-5 h-5 rounded-md! p-0!"
|
||||||
|
size="xs"
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<X
|
||||||
|
color="var(--muted-foreground)"
|
||||||
|
className="opacity-60"
|
||||||
|
size={18}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<Card
|
<Card
|
||||||
ref={inputBoxRef}
|
ref={inputBoxRef}
|
||||||
className={cn(
|
className={cn(
|
||||||
|
|
@ -236,5 +307,6 @@ export default function InputComponent({
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,10 @@ function MessageComponent({
|
||||||
// Message states
|
// Message states
|
||||||
const { load } = useStorage();
|
const { load } = useStorage();
|
||||||
const { send } = useMTP();
|
const { send } = useMTP();
|
||||||
|
const [ownId, setOwnId] = useState(0);
|
||||||
|
useEffect(() => {
|
||||||
|
load("user_id").then(setOwnId);
|
||||||
|
}, [load]);
|
||||||
const messageStateReadUpdate = useCallback(async () => {
|
const messageStateReadUpdate = useCallback(async () => {
|
||||||
const readConfirmations = await load("settings.read_confirmations");
|
const readConfirmations = await load("settings.read_confirmations");
|
||||||
|
|
||||||
|
|
@ -84,7 +88,7 @@ function MessageComponent({
|
||||||
}
|
}
|
||||||
}, [load, message.SendTime, user?.UserId, send]);
|
}, [load, message.SendTime, user?.UserId, send]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (message.SentBySelf) return;
|
if (message.SenderId === ownId || ownId === 0) return;
|
||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
|
|
@ -113,7 +117,13 @@ function MessageComponent({
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [message.MessageState, load, messageStateReadUpdate, message.SentBySelf]);
|
}, [
|
||||||
|
message.MessageState,
|
||||||
|
load,
|
||||||
|
messageStateReadUpdate,
|
||||||
|
message.SenderId,
|
||||||
|
ownId,
|
||||||
|
]);
|
||||||
|
|
||||||
// Check if message is a url
|
// Check if message is a url
|
||||||
const [isValidURL, setIsValidURL] = useState(false);
|
const [isValidURL, setIsValidURL] = useState(false);
|
||||||
|
|
@ -133,7 +143,11 @@ function MessageComponent({
|
||||||
// pt-3 is to get a gap between messages
|
// pt-3 is to get a gap between messages
|
||||||
className={`${grouped ? "" : "pt-3"} w-full flex justify-start transition-opacity duration-150 ${opacityClass}`}
|
className={`${grouped ? "" : "pt-3"} w-full flex justify-start transition-opacity duration-150 ${opacityClass}`}
|
||||||
>
|
>
|
||||||
{user ? (
|
{user && message.Content ? (
|
||||||
|
<MessageContextMenu
|
||||||
|
content={message.Content}
|
||||||
|
messageId={message.SendTime}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"group hover:bg-muted/50 select-text! relative justify-start flex gap-1 items-center w-full px-2 whitespace-pre-wrap break-all",
|
"group hover:bg-muted/50 select-text! relative justify-start flex gap-1 items-center w-full px-2 whitespace-pre-wrap break-all",
|
||||||
|
|
@ -190,7 +204,10 @@ function MessageComponent({
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center justify-start gap-1">
|
<div className="flex items-center justify-start gap-1">
|
||||||
{message.MessageState === "read" ? (
|
{message.MessageState === "read" ? (
|
||||||
<Check size={12} color="var(--primary-foreground-alt)" />
|
<Check
|
||||||
|
size={12}
|
||||||
|
color="var(--primary-foreground-alt)"
|
||||||
|
/>
|
||||||
) : message.MessageState === "received" ? (
|
) : message.MessageState === "received" ? (
|
||||||
<Check size={12} color="var(--muted-foreground)" />
|
<Check size={12} color="var(--muted-foreground)" />
|
||||||
) : message.MessageState === "sent" ? (
|
) : message.MessageState === "sent" ? (
|
||||||
|
|
@ -204,26 +221,15 @@ function MessageComponent({
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{message.Content ? (
|
|
||||||
<MessageContextMenu
|
|
||||||
content={message.Content}
|
|
||||||
messageId={message.SendTime}
|
|
||||||
>
|
|
||||||
{isValidURL ? (
|
{isValidURL ? (
|
||||||
<Media link={message.Content} />
|
<Media link={message.Content} />
|
||||||
) : (
|
) : (
|
||||||
<Text value={message.Content} />
|
<Text value={message.Content} />
|
||||||
)}
|
)}
|
||||||
</MessageContextMenu>
|
|
||||||
) : (
|
|
||||||
<Skeleton
|
|
||||||
className={`w-25 h-5 ${grouped ? "my-1" : "mb-1"} rounded-sm!`}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
</div>
|
</div>
|
||||||
|
</MessageContextMenu>
|
||||||
) : (
|
) : (
|
||||||
<Skeleton className="h-10 w-30" />
|
<Skeleton className="h-10 w-30" />
|
||||||
)}
|
)}
|
||||||
|
|
@ -235,7 +241,7 @@ export default React.memo(MessageComponent, (prev, next) => {
|
||||||
return (
|
return (
|
||||||
prev.message.SendTime === next.message.SendTime &&
|
prev.message.SendTime === next.message.SendTime &&
|
||||||
prev.message.Content === next.message.Content &&
|
prev.message.Content === next.message.Content &&
|
||||||
prev.message.SentBySelf === next.message.SentBySelf &&
|
prev.message.SenderId === next.message.SenderId &&
|
||||||
prev.message.MessageState === next.message.MessageState &&
|
prev.message.MessageState === next.message.MessageState &&
|
||||||
prev.message.failed === next.message.failed &&
|
prev.message.failed === next.message.failed &&
|
||||||
prev.message.decryptionFailed === next.message.decryptionFailed &&
|
prev.message.decryptionFailed === next.message.decryptionFailed &&
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ import {
|
||||||
import { Pin, Clipboard, Pen, Reply, Forward, Trash } from "lucide-react";
|
import { Pin, Clipboard, Pen, Reply, Forward, Trash } from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import type { ReactElement, ReactNode } from "react";
|
import type { ReactElement, ReactNode } from "react";
|
||||||
|
import { useChat } from "../context";
|
||||||
|
|
||||||
async function copyText(text: string) {
|
async function copyText(text: string) {
|
||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
|
|
@ -146,6 +147,8 @@ function MessageMenuContent({
|
||||||
const { Content, Group, Item, Separator, Sub, SubContent, SubTrigger } =
|
const { Content, Group, Item, Separator, Sub, SubContent, SubTrigger } =
|
||||||
components;
|
components;
|
||||||
|
|
||||||
|
const { setReplyTo } = useChat();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Content>
|
<Content>
|
||||||
<Group>
|
<Group>
|
||||||
|
|
@ -172,7 +175,12 @@ function MessageMenuContent({
|
||||||
<Item disabled className="flex justify-between">
|
<Item disabled className="flex justify-between">
|
||||||
<p>Edit Message</p> <Pen />
|
<p>Edit Message</p> <Pen />
|
||||||
</Item>
|
</Item>
|
||||||
<Item disabled className="flex justify-between">
|
<Item
|
||||||
|
className="flex justify-between"
|
||||||
|
onClick={() => {
|
||||||
|
setReplyTo(messageId);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<p>Reply</p> <Reply />
|
<p>Reply</p> <Reply />
|
||||||
</Item>
|
</Item>
|
||||||
<Item disabled className="flex justify-between">
|
<Item disabled className="flex justify-between">
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ import {
|
||||||
} from "@tensamin/crypto/chatSecret";
|
} from "@tensamin/crypto/chatSecret";
|
||||||
import { useStorage } from "@tensamin/storage/context";
|
import { useStorage } from "@tensamin/storage/context";
|
||||||
import { useMTP } from "@tensamin/mtp";
|
import { useMTP } from "@tensamin/mtp";
|
||||||
import { log } from "@tensamin/shared/log";
|
import { log, toast } from "@tensamin/shared/log";
|
||||||
import { useSession } from "@tensamin/storage/session";
|
import { useSession } from "@tensamin/storage/session";
|
||||||
import { useUser } from "@tensamin/user/context";
|
import { useUser } from "@tensamin/user/context";
|
||||||
|
|
||||||
|
|
@ -96,6 +96,44 @@ function protocolBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
|
||||||
return new Uint8Array(bytes);
|
return new Uint8Array(bytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SendMessageGet = (
|
||||||
|
type: "MessageGet",
|
||||||
|
data: { SendTime: number },
|
||||||
|
) => Promise<{ data: RawMessage }>;
|
||||||
|
|
||||||
|
type GetChatSecret = (userId: number) => Promise<Uint8Array | null>;
|
||||||
|
|
||||||
|
export async function fetchReplyMessage({
|
||||||
|
replyTo,
|
||||||
|
send,
|
||||||
|
getChatSecret,
|
||||||
|
}: {
|
||||||
|
replyTo: number;
|
||||||
|
ownId: number;
|
||||||
|
chatUserId: number;
|
||||||
|
send: SendMessageGet;
|
||||||
|
getChatSecret: GetChatSecret;
|
||||||
|
}) {
|
||||||
|
const value = await send("MessageGet", {
|
||||||
|
SendTime: replyTo,
|
||||||
|
});
|
||||||
|
const chatSecret = await getChatSecret(value.data.SenderId);
|
||||||
|
|
||||||
|
if (!chatSecret) {
|
||||||
|
throw new Error("Missing chat secret");
|
||||||
|
}
|
||||||
|
|
||||||
|
const decryptedContent = await decryptChatText(
|
||||||
|
chatSecret,
|
||||||
|
value.data.Content,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...value.data,
|
||||||
|
Content: decryptedContent,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default function Provider({ children }: { children: ReactNode }) {
|
export default function Provider({ children }: { children: ReactNode }) {
|
||||||
const { load } = useStorage();
|
const { load } = useStorage();
|
||||||
const { send, subscribePush } = useMTP();
|
const { send, subscribePush } = useMTP();
|
||||||
|
|
@ -343,13 +381,17 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
[currentChatSecret, send, userIdValue],
|
[currentChatSecret, send, userIdValue],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const [ownId, setOwnId] = useState(0);
|
||||||
|
useEffect(() => {
|
||||||
|
load("user_id").then(setOwnId);
|
||||||
|
}, [load]);
|
||||||
const addLiveMessage = useCallback(
|
const addLiveMessage = useCallback(
|
||||||
(message: RawMessage) => {
|
(message: RawMessage) => {
|
||||||
const localId =
|
const localId =
|
||||||
globalThis.crypto?.randomUUID?.() ??
|
globalThis.crypto?.randomUUID?.() ??
|
||||||
`${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
`${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||||
|
|
||||||
if (!message.SentBySelf) {
|
if (message.SenderId !== ownId) {
|
||||||
moveUserIdToTop(userIdValue);
|
moveUserIdToTop(userIdValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -374,7 +416,7 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
[userIdValue, moveUserIdToTop],
|
[userIdValue, moveUserIdToTop, ownId],
|
||||||
);
|
);
|
||||||
|
|
||||||
const clearLiveMessages = useCallback(() => {
|
const clearLiveMessages = useCallback(() => {
|
||||||
|
|
@ -475,6 +517,9 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
});
|
});
|
||||||
}, [addLiveMessage, currentChatSecret, send, subscribePush, userIdValue]);
|
}, [addLiveMessage, currentChatSecret, send, subscribePush, userIdValue]);
|
||||||
|
|
||||||
|
// Replys
|
||||||
|
const [replyTo, setReplyTo] = useState<number | undefined>(undefined);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<context.Provider
|
<context.Provider
|
||||||
|
|
@ -489,6 +534,8 @@ export default function Provider({ children }: { children: ReactNode }) {
|
||||||
inputBoxRef,
|
inputBoxRef,
|
||||||
error,
|
error,
|
||||||
errorDescription,
|
errorDescription,
|
||||||
|
replyTo,
|
||||||
|
setReplyTo,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|
@ -510,6 +557,8 @@ type contextType = {
|
||||||
inputBoxRef: React.RefObject<HTMLDivElement | null>;
|
inputBoxRef: React.RefObject<HTMLDivElement | null>;
|
||||||
error: string;
|
error: string;
|
||||||
errorDescription: string;
|
errorDescription: string;
|
||||||
|
replyTo: number | undefined;
|
||||||
|
setReplyTo: (value: number | undefined) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useChat(): contextType {
|
export function useChat(): contextType {
|
||||||
|
|
@ -519,3 +568,66 @@ export function useChat(): contextType {
|
||||||
}
|
}
|
||||||
return ctx;
|
return ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useReplyMessage() {
|
||||||
|
const { send } = useMTP();
|
||||||
|
const { load } = useStorage();
|
||||||
|
const { replyTo, setReplyTo, getChatSecret, userId } = useChat();
|
||||||
|
const [ownId, setOwnId] = useState(0);
|
||||||
|
const [replyMessage, setReplyMessage] = useState<RawMessage | undefined>();
|
||||||
|
|
||||||
|
const handleReplyError = useCallback(
|
||||||
|
(err: unknown) => {
|
||||||
|
log(1, "chat", "red", "Failed to get reply message", err);
|
||||||
|
toast("error", "Failed to get reply message", String(err));
|
||||||
|
setReplyTo(undefined);
|
||||||
|
setReplyMessage(undefined);
|
||||||
|
},
|
||||||
|
[setReplyTo],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load("user_id").then((value) => {
|
||||||
|
setOwnId(Number(value));
|
||||||
|
});
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!replyTo || !ownId) {
|
||||||
|
setReplyMessage(undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let active = true;
|
||||||
|
setReplyMessage(undefined);
|
||||||
|
|
||||||
|
void fetchReplyMessage({
|
||||||
|
replyTo,
|
||||||
|
ownId,
|
||||||
|
chatUserId: userId,
|
||||||
|
send,
|
||||||
|
getChatSecret,
|
||||||
|
})
|
||||||
|
.then((message) => {
|
||||||
|
if (active) {
|
||||||
|
setReplyMessage(message);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (active) {
|
||||||
|
handleReplyError(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [replyTo, ownId, userId, send, getChatSecret, handleReplyError]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
ownId,
|
||||||
|
replyTo,
|
||||||
|
replyMessage,
|
||||||
|
replyUserId: replyMessage?.SenderId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { useInfiniteQuery } from "@tanstack/react-query";
|
import { useInfiniteQuery } from "@tanstack/react-query";
|
||||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||||
import { failedUser } from "@tensamin/shared/data";
|
|
||||||
import { useStorage } from "@tensamin/storage/context";
|
|
||||||
import { useUser, type User } from "@tensamin/user/context";
|
|
||||||
|
|
||||||
import InputComponent from "./components/input";
|
import InputComponent from "./components/input";
|
||||||
import Message from "./components/message";
|
import Message from "./components/message";
|
||||||
|
|
@ -15,6 +12,8 @@ import {
|
||||||
type LiveMessage,
|
type LiveMessage,
|
||||||
type RawMessage,
|
type RawMessage,
|
||||||
} from "./values";
|
} from "./values";
|
||||||
|
import Wrapper from "@tensamin/user/wrapper";
|
||||||
|
import { Skeleton } from "@tensamin/ui";
|
||||||
|
|
||||||
type MessageChunk = {
|
type MessageChunk = {
|
||||||
key: string;
|
key: string;
|
||||||
|
|
@ -83,9 +82,6 @@ export default function Screen() {
|
||||||
error,
|
error,
|
||||||
errorDescription,
|
errorDescription,
|
||||||
} = useChat();
|
} = useChat();
|
||||||
const { get: getUser } = useUser();
|
|
||||||
const { load } = useStorage();
|
|
||||||
|
|
||||||
const scrollRef = React.useRef<HTMLDivElement | null>(null);
|
const scrollRef = React.useRef<HTMLDivElement | null>(null);
|
||||||
const topSentinelRef = React.useRef<HTMLDivElement | null>(null);
|
const topSentinelRef = React.useRef<HTMLDivElement | null>(null);
|
||||||
const didInitialScrollRef = React.useRef(false);
|
const didInitialScrollRef = React.useRef(false);
|
||||||
|
|
@ -97,9 +93,6 @@ export default function Screen() {
|
||||||
const isFetchingNextPageRef = React.useRef(false);
|
const isFetchingNextPageRef = React.useRef(false);
|
||||||
const fetchNextPageRef = React.useRef<(() => void) | null>(null);
|
const fetchNextPageRef = React.useRef<(() => void) | null>(null);
|
||||||
|
|
||||||
const [messageUsers, setMessageUsers] = React.useState<
|
|
||||||
Record<string, User | undefined>
|
|
||||||
>({});
|
|
||||||
const [lastLiveMessageCount, setLastLiveMessageCount] = React.useState(0);
|
const [lastLiveMessageCount, setLastLiveMessageCount] = React.useState(0);
|
||||||
const [didInitialScroll, setDidInitialScroll] = React.useState(false);
|
const [didInitialScroll, setDidInitialScroll] = React.useState(false);
|
||||||
const [viewportHeight, setViewportHeight] = React.useState(0);
|
const [viewportHeight, setViewportHeight] = React.useState(0);
|
||||||
|
|
@ -144,41 +137,6 @@ export default function Screen() {
|
||||||
setLastLiveMessageCount(0);
|
setLastLiveMessageCount(0);
|
||||||
}, [clearLiveMessages, userId]);
|
}, [clearLiveMessages, userId]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (!hasValidChatUser) {
|
|
||||||
setMessageUsers({});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let active = true;
|
|
||||||
|
|
||||||
const loadMessageUser = async (
|
|
||||||
key: string,
|
|
||||||
resolveUserId: () => Promise<number>,
|
|
||||||
) => {
|
|
||||||
try {
|
|
||||||
const resolvedUserId = await resolveUserId();
|
|
||||||
const value = await getUser(resolvedUserId);
|
|
||||||
|
|
||||||
if (active) {
|
|
||||||
setMessageUsers((prev) => ({ ...prev, [key]: value }));
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
if (active) {
|
|
||||||
setMessageUsers((prev) => ({ ...prev, [key]: failedUser }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
setMessageUsers({});
|
|
||||||
void loadMessageUser("peer", async () => userId);
|
|
||||||
void loadMessageUser("own", async () => Number(await load("user_id")));
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
active = false;
|
|
||||||
};
|
|
||||||
}, [getUser, hasValidChatUser, load, userId]);
|
|
||||||
|
|
||||||
const historicalMessages = React.useMemo(() => {
|
const historicalMessages = React.useMemo(() => {
|
||||||
const pages = messagesQuery.data?.pages ?? [];
|
const pages = messagesQuery.data?.pages ?? [];
|
||||||
const seenSendTimes = new Set<number>();
|
const seenSendTimes = new Set<number>();
|
||||||
|
|
@ -559,20 +517,22 @@ export default function Screen() {
|
||||||
const lastMessage = messages[messageIndex - 1];
|
const lastMessage = messages[messageIndex - 1];
|
||||||
const isGrouped =
|
const isGrouped =
|
||||||
lastMessage &&
|
lastMessage &&
|
||||||
lastMessage.SentBySelf === message.SentBySelf &&
|
lastMessage.SenderId === message.SenderId &&
|
||||||
Math.round(lastMessage.SendTime / 10000) ===
|
Math.round(lastMessage.SendTime / 10000) ===
|
||||||
Math.round(message.SendTime / 10000);
|
Math.round(message.SendTime / 10000);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<Wrapper
|
||||||
|
userId={message.SenderId}
|
||||||
|
loading={<Skeleton className="w-30 h-5" />}
|
||||||
|
component={(user) => (
|
||||||
<Message
|
<Message
|
||||||
key={getMessageRenderKey(message)}
|
key={getMessageRenderKey(message)}
|
||||||
grouped={isGrouped}
|
grouped={isGrouped}
|
||||||
message={message}
|
message={message}
|
||||||
user={
|
user={user}
|
||||||
message.SentBySelf
|
/>
|
||||||
? (messageUsers.own ?? null)
|
)}
|
||||||
: (messageUsers.peer ?? null)
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,6 @@ export default function Provider(props: { children: React.ReactNode }) {
|
||||||
...data.Message,
|
...data.Message,
|
||||||
Content: content ?? "Failed to decrypt message",
|
Content: content ?? "Failed to decrypt message",
|
||||||
decryptionFailed: content === null,
|
decryptionFailed: content === null,
|
||||||
SentBySelf: false,
|
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -68,13 +68,14 @@ const callSecretEnvelopeRequest = z.object({
|
||||||
|
|
||||||
export const Message = z.object({
|
export const Message = z.object({
|
||||||
NotEncrypted: z.boolean().optional(),
|
NotEncrypted: z.boolean().optional(),
|
||||||
SentBySelf: z.boolean().optional(),
|
SenderId: z.number(),
|
||||||
SendTime: z.number(),
|
SendTime: z.number(),
|
||||||
Content: z.base64(),
|
Content: z.base64(),
|
||||||
Files: z.array(fileFromMessage).optional(),
|
Files: z.array(fileFromMessage).optional(),
|
||||||
Tint: z.string().length(7).startsWith("#").optional(),
|
Tint: z.string().length(7).startsWith("#").optional(),
|
||||||
Avatar: z.boolean().optional(),
|
Avatar: z.boolean().optional(),
|
||||||
Display: z.boolean().optional(),
|
Display: z.boolean().optional(),
|
||||||
|
ReplyId: z.number().optional(),
|
||||||
MessageState: z
|
MessageState: z
|
||||||
.enum(["read", "received", "sent", "sending", "awaiting"]) // awaiting for 'internal' use
|
.enum(["read", "received", "sent", "sending", "awaiting"]) // awaiting for 'internal' use
|
||||||
.default("received"),
|
.default("received"),
|
||||||
|
|
@ -201,6 +202,12 @@ export const mtp = {
|
||||||
Message,
|
Message,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
MessageGet: {
|
||||||
|
request: z.object({
|
||||||
|
SendTime: z.number(),
|
||||||
|
}),
|
||||||
|
response: Message,
|
||||||
|
},
|
||||||
MessagesGet: {
|
MessagesGet: {
|
||||||
request: z.object({
|
request: z.object({
|
||||||
UserId: z.number(),
|
UserId: z.number(),
|
||||||
|
|
|
||||||
8373
pnpm-lock.yaml
generated
8373
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
|
|
@ -71,6 +71,7 @@ type_maps:
|
||||||
MessageLive: 59
|
MessageLive: 59
|
||||||
MessageOtherIota: 60
|
MessageOtherIota: 60
|
||||||
MessageChunk: 61
|
MessageChunk: 61
|
||||||
|
MessageGet: 143
|
||||||
MessagesGet: 62
|
MessagesGet: 62
|
||||||
PushNotification: 63
|
PushNotification: 63
|
||||||
ReadNotification: 64
|
ReadNotification: 64
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue