Skip to content

Commit

Permalink
feat: 커서공유 테스트
Browse files Browse the repository at this point in the history
  • Loading branch information
LeHiHo committed Jan 24, 2024
1 parent b638a60 commit c5b93a4
Show file tree
Hide file tree
Showing 8 changed files with 195 additions and 29 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"react-beautiful-dnd": "^13.1.1",
"react-dom": "^18.2.0",
"react-hook-form": "^7.49.2",
"react-icons": "^5.0.1",
"react-infinite-scroller": "^1.2.6",
"react-kakao-maps-sdk": "^1.1.24",
"react-modal": "^3.16.1",
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/api/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ export const pubConnectMember = (pubMember: pubMember, tripId: string) => {
destination: `/pub/trips/${tripId}/connectMember`,
body: JSON.stringify(pubMember),
});
console.log('입장발생');
};

// 멤버 여정 페이지 퇴장 이벤트 발생시
Expand All @@ -162,6 +163,7 @@ export const pubDisconnectMember = (pubMember: pubMember, tripId: string) => {
destination: `/pub/trips/${tripId}/disconnectMember`,
body: JSON.stringify(pubMember),
});
console.log('퇴장발생');
};

// 여정 편집 페이지 입장 이벤트 발생시(모든 sub 다받음)
Expand Down Expand Up @@ -206,5 +208,4 @@ export const pubCursor = (pubCursor: pubCursor, tripId: string) => {
destination: `/pub/trips/${tripId}/cursor`,
body: JSON.stringify(pubCursor),
});
console.log(pubCursor);
};
94 changes: 94 additions & 0 deletions src/components/Plan/PlanCursor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { useEffect, useState, useContext } from 'react';
import { BsFillCursorFill } from 'react-icons/bs';
import { pubCursor } from '@api/socket';
import { socketContext } from '@hooks/useSocket';
import { useGetTripsAuthority } from '@hooks/useGetTripsAuthority';

type TripCursorData = {
memberId: number;
x: number;
y: number;
name: string;
};

type PlanCursorProps = {
date: string;
};

const PlanCursor = ({ date }: PlanCursorProps) => {
const token = localStorage.getItem('accessToken');
const { memberId } = useGetTripsAuthority();
const { callBackPub, tripId, tripMember } = useContext(socketContext);
const [position, setPosition] = useState({ x: 0, y: 0 });

const myName = tripMember?.data?.tripMembers.find(
(member) => member.memberId === memberId,
);

useEffect(() => {
const handleMouseMove = (e: MouseEvent) => {
setPosition({ x: e.clientX, y: e.clientY });
};
const cursorStyle = (style: string): void => {
document.querySelectorAll('*').forEach((el) => {
const element = el as HTMLElement;
element.style.cursor = style;
});
};
cursorStyle('none');
document.addEventListener('mousemove', handleMouseMove);
return () => {
cursorStyle('auto');
document.removeEventListener('mousemove', handleMouseMove);
};
}, []);

// useEffect(() => {
// if (token && position && myName && date && tripId) {
// const timeoutId = setTimeout(() => {
// callBackPub(() =>
// pubCursor(
// {
// token: token,
// visitDate: date,
// x: position.x,
// y: position.y,
// },
// tripId,
// ),
// );
// }, 1000);

// return () => clearTimeout(timeoutId);
// }
// }, [position]);

useEffect(() => {
if (token && position && myName && date && tripId) {
callBackPub(() =>
pubCursor(
{
token: token,
visitDate: date,
x: position.x,
y: position.y,
},
tripId,
),
);
}
}, [position]);

return (
<div
className="pointer-events-none fixed z-50 w-full -translate-x-2 -translate-y-2 transform"
style={{ left: `${position.x}px`, top: `${position.y}px` }}>
<BsFillCursorFill size={15} color="blue" className="scale-x-[-1]" />
<div className="text-bold text-blue absolute left-1 top-2 p-1 text-center text-xs">
{myName?.name}
</div>
</div>
);
};

export default PlanCursor;
6 changes: 5 additions & 1 deletion src/components/Plan/PlanItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { visitDateState, isEditState } from '@recoil/socket';
import { pubGetPathAndItems, pubUpdateTransportation } from '@api/socket';
import { tapState } from '@recoil/plan';
import { useGetTripsAuthority } from '@hooks/useGetTripsAuthority';
import PlanCursor from './PlanCursor';
import PlanOtherCursor from './PlanOtherCursor';

type PlanItemProps = {
date: string;
Expand Down Expand Up @@ -62,8 +64,10 @@ const PlanItem: React.FC<PlanItemProps> = ({ date, day }) => {

return (
<>
{tripPath && <TripMap paths={tripPath.data?.paths || []} />}
<PlanCursor date={date} />
<PlanOtherCursor />

{tripPath && <TripMap paths={tripPath.data?.paths || []} />}
<div className="mb-[31px] mt-[31px] flex items-center justify-between">
{tripAuthority !== 'WRITE' || isEdit ? (
<div />
Expand Down
63 changes: 63 additions & 0 deletions src/components/Plan/PlanOtherCursor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { useEffect, useState, useContext } from 'react';
import { BsFillCursorFill } from 'react-icons/bs';
import { pubCursor } from '@api/socket';
import { socketContext } from '@hooks/useSocket';
import { useGetTripsAuthority } from '@hooks/useGetTripsAuthority';

type TripCursorData = {
memberId: number;
x: number;
y: number;
name: string;
};

type PlanCursorProps = {
date: string;
};

const PlanOtherCursor = () => {
const { memberId } = useGetTripsAuthority();
const { tripCursor } = useContext(socketContext);
const [otherCursors, setOtherCursors] = useState<TripCursorData[]>([]);

console.log(otherCursors);
useEffect(() => {
if (
tripCursor &&
tripCursor.data &&
tripCursor.data.memberId !== memberId
) {
setOtherCursors((prevCursors) => {
const existingCursorIndex = prevCursors.findIndex(
(cursor) => cursor.memberId === tripCursor.data!.memberId,
);

if (existingCursorIndex !== -1) {
const updatedCursors = [...prevCursors];
updatedCursors[existingCursorIndex] = tripCursor.data!;
return updatedCursors;
} else {
return [...prevCursors, tripCursor.data!];
}
});
}
}, [tripCursor, memberId]);

return (
<>
{otherCursors.map((cursor, index) => (
<div
key={index}
className="pointer-events-none fixed z-50 w-full -translate-x-2 -translate-y-2 transform"
style={{ left: `${cursor.x}px`, top: `${cursor.y}px` }}>
<BsFillCursorFill size={15} color="red" className="scale-x-[-1]" />
<div className="text-bold absolute left-1 top-2 p-1 text-center text-xs text-red">
{cursor.name}
</div>
</div>
))}
</>
);
};

export default PlanOtherCursor;
19 changes: 0 additions & 19 deletions src/components/Plan/PlanSectionTop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
pubEnterMember,
pubConnectMember,
pubDisconnectMember,
pubCursor,
} from '@api/socket';
import { useEffect } from 'react';
import { useRecoilState } from 'recoil';
Expand All @@ -34,7 +33,6 @@ const PlanSectionTop = () => {
tripPath,
tripMember,
tripBudget,
tripCursor,
} = useContext(socketContext);
const [, setVisitDate] = useRecoilState(visitDateState);
const { startDate, endDate } = useGetTrips();
Expand All @@ -47,8 +45,6 @@ const PlanSectionTop = () => {
({ DayArr, DateArr } = calculateDayAndDate(startDate, endDate));
}

console.log(tripCursor);

useEffect(() => {
if (startDate) {
setVisitDate({ visitDate: startDate });
Expand Down Expand Up @@ -84,21 +80,6 @@ const PlanSectionTop = () => {
}
}, [isEnter]);

// useEffect(() => {
// callBackPub(() =>
// pubCursor(
// {
// token:
// 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI4MCIsImF1dGgiOiJST0xFX1VTRVIiLCJleHAiOjE3MDU5OTQ4NDJ9.nu7XavOKvKaFYJB77bmPkkYV3rLvfra2zGxa9d9kArwS235CiKi_5UTzm4HqanUIFonhXmS0yxFBrjchlpPFQg',
// visitDate: '2024-02-07',
// x: 123.213,
// y: 92.531,
// },
// tripId,
// ),
// );
// }, []);

return (
<div className="min-h-screen">
<BackBox
Expand Down
27 changes: 19 additions & 8 deletions src/hooks/useSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
SocketContextType,
} from '@/@types/service';
import { createContext } from 'react';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { useRecoilValue } from 'recoil';
import { visitDateState } from '@recoil/socket';
Expand Down Expand Up @@ -45,14 +45,15 @@ export const useSocket = () => {
const [tripBudget, setTripBudget] = useState<subBudgetRes | null>(null);
const [tripCursor, setTripCursor] = useState<subCursorRes | null>(null);

const [socketCallback, setSocketCallback] = useState<(() => void) | null>(
null,
);
const socketCallbackRef = useRef<(() => void) | null>(null);

const callBackPub = (callback: () => void): void => {
setSocketCallback(() => callback);
// socketCallbackRef에 새로운 콜백을 할당
socketCallbackRef.current = callback;
};

console.log(socketCallbackRef.current);

const socketConnect = (tripId: string, visitDate: string) => {
socketClient.onConnect = () => {
subInfo(tripId, (res) => {
Expand Down Expand Up @@ -91,8 +92,8 @@ export const useSocket = () => {
}
});

if (socketCallback) {
socketCallback();
if (socketCallbackRef.current) {
socketCallbackRef.current();
}
};

Expand All @@ -103,11 +104,13 @@ export const useSocket = () => {
if (tripId && visitDate) {
socketConnect(tripId, visitDate.visitDate);
}
console.log('소켓연결');

return () => {
socketClient.deactivate();
console.log('소켓해제');
};
}, [tripId, visitDate, socketCallback]);
}, [tripId, visitDate]);

return {
tripInfo,
Expand All @@ -120,3 +123,11 @@ export const useSocket = () => {
callBackPub,
};
};

// const [socketCallback, setSocketCallback] = useState<(() => void) | null>(
// null,
// );

// const callBackPub = (callback: () => void): void => {
// setSocketCallback(() => callback);
// };

0 comments on commit c5b93a4

Please sign in to comment.