Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KeepMemo #444

Merged
merged 14 commits into from
Dec 2, 2024
Merged
16 changes: 16 additions & 0 deletions server/src/database/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,19 @@ export async function getMatchedUser(userId: UserID): Promise<Result<User[]>> {
return Err(e);
}
}

export async function matchWithMemo(userId: UserID) {
try {
const result = await prisma.relationship.create({
data: {
status: "MATCHED",
sendingUserId: userId,
receivingUserId: 0, //KeepメモのUserId
},
});

return result;
} catch (error) {
return Err(error);
}
}
15 changes: 13 additions & 2 deletions server/src/router/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import express, { type Request, type Response } from "express";
import {
getPendingRequestsFromUser,
getPendingRequestsToUser,
matchWithMemo,
} from "../database/requests";
import {
createUser,
Expand Down Expand Up @@ -124,10 +125,20 @@ router.get("/id/:id", async (req: Request, res: Response) => {
// INSERT INTO "User" VALUES (body...)
router.post("/", async (req: Request, res: Response) => {
const partialUser = InitUserSchema.safeParse(req.body);
if (!partialUser.success) return res.status(400).send("invalid format");
if (!partialUser.success)
return res.status(400).send({
error: "Invalid input format",
details: partialUser.error.errors,
});

const user = await createUser(partialUser.data);
if (!user.ok) return res.status(500).send();
if (!user.ok) return res.status(500).send({ error: "Failed to create user" });

//ユーザー作成と同時にメモとマッチング
const result = await matchWithMemo(user.value.id);
if ("ok" in result && !result.ok) {
return res.status(500).send({ error: "Failed to match user with memo" });
}
res.status(201).json(user.value);
});

Expand Down
14 changes: 12 additions & 2 deletions web/api/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,24 @@ export async function sendDM(
return res.json();
}

export async function getDM(friendId: UserID): Promise<DMRoom> {
export async function getDM(friendId: UserID): Promise<
DMRoom & {
name: string;
thumbnail: string;
}
> {
console.log("リクエスト先", endpoints.dmWith(friendId));
const res = await credFetch("GET", endpoints.dmWith(friendId));
console.log("いい");
if (res.status === 401) throw new ErrUnauthorized();
if (res.status !== 200)
throw new Error(
`getDM() failed: expected status code 200, got ${res.status}`,
);
const json: DMRoom = await res.json();
const json: DMRoom & {
name: string;
thumbnail: string;
} = await res.json();
if (!Array.isArray(json?.messages)) return json;
for (const m of json.messages) {
m.createdAt = new Date(m.createdAt);
Expand Down
39 changes: 39 additions & 0 deletions web/app/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"use client";
import { useEffect, useState } from "react";
import * as chat from "~/api/chat/chat";
import { RoomWindow } from "~/components/chat/RoomWindow";

export default function Page({ params }: { params: { id: string } }) {
const id = Number.parseInt(params.id);
console.log("IDだよ", id);
const [room, setRoom] = useState<
| ({
id: number;
isDM: true;
messages: {
id: number;
creator: number;
createdAt: Date;
content: string;
edited: boolean;
}[];
} & {
name: string;
thumbnail: string;
})
| null
>(null);
useEffect(() => {
(async () => {
const room = await chat.getDM(id);
setRoom(room);
})();
}, [id]);

return (
<>
<p>idは{id}です。</p>
{room ? <RoomWindow friendId={id} room={room} /> : <p>データないよ</p>}
</>
);
}
14 changes: 1 addition & 13 deletions web/app/chat/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"use client";

import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { useRoomsOverview } from "~/api/chat/hooks";
import RoomList from "~/components/chat/RoomList";
import { RoomWindow } from "~/components/chat/RoomWindow";
import FullScreenCircularProgress from "~/components/common/FullScreenCircularProgress";

export default function Chat() {
Expand All @@ -16,18 +14,8 @@ export default function Chat() {
}

function ChatListContent() {
const searchParams = useSearchParams();

const friendId = searchParams.get("friendId");

const { state } = useRoomsOverview();

return friendId ? (
<>
<p>Chat - friend Id: {friendId}</p>
<RoomWindow />
</>
) : state.current === "loading" ? (
return state.current === "loading" ? (
<FullScreenCircularProgress />
) : state.current === "error" ? (
<p className="decoration-red">Error: {state.error.message}</p>
Expand Down
16 changes: 8 additions & 8 deletions web/components/chat/MessageInput.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import type { DMOverview, SendMessage, UserID } from "common/types";
import type { SendMessage, UserID } from "common/types";
import { parseContent } from "common/zod/methods";
import { useEffect, useState } from "react";
import { MdSend } from "react-icons/md";

type Props = {
send: (to: UserID, m: SendMessage) => void;
room: DMOverview;
friendId: UserID;
};

const crossRoomMessageState = new Map<number, string>();

export function MessageInput({ send, room }: Props) {
export function MessageInput({ send, friendId }: Props) {
const [message, _setMessage] = useState<string>("");
const [error, setError] = useState<string | null>(null);

function setMessage(m: string) {
_setMessage(m);
crossRoomMessageState.set(room.friendId, m);
crossRoomMessageState.set(friendId, m);
}

useEffect(() => {
_setMessage(crossRoomMessageState.get(room.friendId) || "");
}, [room.friendId]);
_setMessage(crossRoomMessageState.get(friendId) || "");
}, [friendId]);

function submit(e: React.FormEvent) {
e.preventDefault();
Expand All @@ -34,7 +34,7 @@ export function MessageInput({ send, room }: Props) {
}

if (message.trim()) {
send(room.friendId, { content: message });
send(friendId, { content: message });
setMessage("");
}
}
Expand All @@ -50,7 +50,7 @@ export function MessageInput({ send, room }: Props) {
return;
}
if (message.trim()) {
send(room.friendId, { content: message });
send(friendId, { content: message });
setMessage("");
}
}
Expand Down
16 changes: 14 additions & 2 deletions web/components/chat/RoomHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
import type { DMOverview } from "common/types";
import Link from "next/link";
import { MdArrowBack } from "react-icons/md";
import UserAvatar from "../human/avatar";

type Props = {
room: DMOverview;
room: {
isDM: true;
id: number;
messages: {
id: number;
creator: number;
createdAt: Date;
content: string;
edited: boolean;
}[];
} & {
name: string;
thumbnail: string;
};
};

export function RoomHeader(props: Props) {
Expand Down
9 changes: 1 addition & 8 deletions web/components/chat/RoomList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,8 @@ type RoomListProps = {
export function RoomList(props: RoomListProps) {
const { roomsData } = props;
const router = useRouter();

/**
* FIXME:
* React Router が使えなくなったので、一時的に room の情報を URL に載せることで状態管理
*/
const navigateToRoom = (room: Extract<RoomOverview, { isDM: true }>) => {
router.push(
`./?friendId=${room.friendId}&roomData=${encodeURIComponent(JSON.stringify(room))}`,
);
router.push(`/chat/${room.friendId}`);
};

return (
Expand Down
55 changes: 31 additions & 24 deletions web/components/chat/RoomWindow.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import type {
DMOverview,
Message,
MessageID,
SendMessage,
UserID,
} from "common/types";
"use client";
import type { Message, MessageID, SendMessage, UserID } from "common/types";
import type { Content } from "common/zod/types";
import { useSearchParams } from "next/navigation";
import { useSnackbar } from "notistack";
import { useCallback, useEffect, useRef, useState } from "react";
import * as chat from "~/api/chat/chat";
Expand All @@ -19,13 +13,25 @@ import { socket } from "../data/socket";
import { MessageInput } from "./MessageInput";
import { RoomHeader } from "./RoomHeader";

export function RoomWindow() {
// FIXME: React Router が使えなくなったので、一時的に room の情報を URL に載せることで状態管理
const searchParams = useSearchParams();
const roomData = searchParams.get("roomData");
const room = roomData
? (JSON.parse(decodeURIComponent(roomData)) as DMOverview)
: null;
type Props = {
friendId: UserID;
room: {
id: number;
messages: {
id: number;
creator: number;
createdAt: Date;
content: string;
edited: boolean;
}[];
isDM: true;
} & {
name: string;
thumbnail: string;
};
};
export function RoomWindow(props: Props) {
const { friendId, room } = props;

if (!room) {
return (
Expand All @@ -36,7 +42,7 @@ export function RoomWindow() {
const {
state: { data: myId },
} = useMyID();
const { state, reload, write } = useMessages(room.friendId);
const { state, reload, write } = useMessages(friendId);
const [messages, setMessages] = useState(state.data);

useEffect(() => {
Expand Down Expand Up @@ -73,7 +79,7 @@ export function RoomWindow() {
const idToken = await getIdToken();
socket.emit("register", idToken);
socket.on("newMessage", async (msg: Message) => {
if (msg.creator === room.friendId) {
if (msg.creator === friendId) {
appendLocalMessage(msg);
} else {
const creator = await user.get(msg.creator);
Expand All @@ -87,7 +93,7 @@ export function RoomWindow() {
}
});
socket.on("updateMessage", async (msg: Message) => {
if (msg.creator === room.friendId) {
if (msg.creator === friendId) {
updateLocalMessage(msg);
}
});
Expand All @@ -104,6 +110,7 @@ export function RoomWindow() {
};
}, [
room,
friendId,
enqueueSnackbar,
appendLocalMessage,
updateLocalMessage,
Expand Down Expand Up @@ -142,11 +149,11 @@ export function RoomWindow() {
const editedMessage = await chat.updateMessage(
message,
{ content },
room.friendId,
friendId,
);
updateLocalMessage(editedMessage);
},
[updateLocalMessage, room.friendId],
[updateLocalMessage, friendId],
);

const cancelEdit = useCallback(() => {
Expand All @@ -167,7 +174,7 @@ export function RoomWindow() {
<div className="fixed top-14 z-50 w-full bg-white">
<RoomHeader room={room} />
</div>
<div className="absolute top-14 right-0 bottom-14 left-0 flex flex-col overflow-y-auto">
<div className="absolute top-14 right-0 left-0 flex flex-col overflow-y-auto">
{messages && messages.length > 0 ? (
<div className="flex-grow overflow-y-auto p-2" ref={scrollDiv}>
{messages.map((m) => (
Expand Down Expand Up @@ -225,7 +232,7 @@ export function RoomWindow() {
{
label: "削除",
color: "red",
onClick: () => deleteMessage(m.id, room.friendId),
onClick: () => deleteMessage(m.id, friendId),
alert: true,
messages: {
buttonMessage: "削除",
Expand All @@ -248,8 +255,8 @@ export function RoomWindow() {
</div>
)}
</div>
<div className="fixed bottom-0 w-full bg-white p-0">
<MessageInput send={sendDMMessage} room={room} />
<div className="fixed bottom-12 w-full bg-white p-0">
<MessageInput send={sendDMMessage} friendId={friendId} />
</div>
</>
);
Expand Down
Loading
Loading