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

[FE][Refactor] #224 : CanvasWithMap 이벤트 함수를 훅으로 분리 #248

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:

- name: Run Build
run: pnpm build # pnpm을 사용하여 빌드 실행
continue-on-error: false # 빌드 실패 시 워크플로우 실패로 처리
# continue-on-error: false # 빌드 실패 시 워크플로우 실패로 처리

- name: Run Tests
run: pnpm test # pnpm을 사용하여 테스트 실행
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/component/canvas/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export interface ICanvasRefMethods {
}

export const Canvas = forwardRef<ICanvasRefMethods, ICanvasProps>((props, ref) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null!);
const { points, addPoint, undo, redo, undoStack, redoStack } = useUndoRedo([]);
const [startPoint, setStartPoint] = useState<IPoint | null>(null);
const [endPoint, setEndPoint] = useState<IPoint | null>(null);
Expand Down
83 changes: 17 additions & 66 deletions frontend/src/component/canvas/CanvasWithMap.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Canvas, ICanvasRefMethods } from '@/component/canvas/Canvas.tsx';
import { Map, IMapRefMethods } from '@/component/maps/Map.tsx';
import classNames from 'classnames';
import { ICanvasVertex } from '@/utils/screen/canvasUtils.ts';
import { INaverMapVertexPosition } from '@/component/maps/naverMapUtils.ts';
import { useRef, useEffect, useState } from 'react';
import classNames from 'classnames';
import { Canvas, ICanvasRefMethods } from '@/component/canvas/Canvas.tsx';
import { Map } from '@/component/maps/Map.tsx';
import { IMapObject, IMapRefMethods } from '@/component/maps/Map.types.ts';
import { useEventHandlers } from '@/component/canvas/useEventHandlers.tsx';

interface ICanvasWithMapProps {
className?: string;
Expand All @@ -14,32 +14,13 @@ interface ICanvasWithMapProps {
allowCanvas?: boolean;
}

interface IMouseEventState {
isMouseDown: boolean;
mouseDownPosition: { x: number; y: number };
// mouseMovePosition: { x: number; y: number };
mouseDeltaPosition: { x: number; y: number };
}

export interface ILocationObject {
canvas: ICanvasVertex;
map: INaverMapVertexPosition;
}

const MouseEventStateInitialValue = {
isMouseDown: false,
mouseDownPosition: { x: 0, y: 0 },
// mouseMovePosition: { x: 0, y: 0 },
mouseDeltaPosition: { x: 0, y: 0 },
};

export const CanvasWithMap = (props: ICanvasWithMapProps) => {
const mapRefMethods = useRef<IMapRefMethods | null>(null);
const mapElement = useRef<HTMLElement | null>(null);
const canvasRefMethods = useRef<ICanvasRefMethods | null>(null);
const mapElement = useRef<HTMLElement | null>(null);
const canvasElement = useRef<HTMLCanvasElement | null>(null);
const mouseEventState = useRef<IMouseEventState>({ ...MouseEventStateInitialValue });
const [mapObject, setMapObject] = useState<naver.maps.Map | null>(null);

const [mapObject, setMapObject] = useState<IMapObject | null>(null);

useEffect(() => {
if (canvasRefMethods.current?.getCanvasElement)
Expand All @@ -50,46 +31,16 @@ export const CanvasWithMap = (props: ICanvasWithMapProps) => {
mapElement.current = mapRefMethods.current?.getMapContainer() ?? null;
}, [mapObject]);

const initMap = (mapObj: naver.maps.Map | null) => {
setMapObject(mapObj);
};

const handleClick = (event: React.MouseEvent) => {
mapRefMethods.current?.onMouseClickHandler(event);
canvasRefMethods.current?.onMouseClickHandler(event);
};

const handleMouseDown = (event: React.MouseEvent<HTMLElement>) => {
if (!mapElement.current || !canvasElement.current) return;
mouseEventState.current.isMouseDown = true;
mouseEventState.current.mouseDownPosition = { x: event.clientX, y: event.clientY };
canvasRefMethods.current?.onMouseDownHandler(event);
};

const handleMouseMove = (event: React.MouseEvent<HTMLElement>) => {
if (!mapElement.current || !canvasElement.current || !mouseEventState.current.isMouseDown)
return;

// TODO: 쓰로틀링 걸기
mouseEventState.current.mouseDeltaPosition = {
x: -(event.clientX - mouseEventState.current.mouseDownPosition.x),
y: -(event.clientY - mouseEventState.current.mouseDownPosition.y),
};

mapObject?.panBy(
new naver.maps.Point(
mouseEventState.current.mouseDeltaPosition.x,
mouseEventState.current.mouseDeltaPosition.y,
),
);

canvasRefMethods.current?.onMouseMoveHandler(event);
};
const { handleClick, handleMouseDown, handleMouseMove, handleMouseUp } = useEventHandlers(
canvasElement.current,
canvasRefMethods.current,
mapElement.current,
mapRefMethods.current,
mapObject,
);

const handleMouseUp = (event: React.MouseEvent) => {
if (!mapElement.current || !canvasElement.current) return;
mouseEventState.current = { ...MouseEventStateInitialValue };
canvasRefMethods.current?.onMouseUpHandler(event);
const initMap = (mapObj: IMapObject | null) => {
setMapObject(mapObj);
};

return (
Expand Down
86 changes: 86 additions & 0 deletions frontend/src/component/canvas/useEventHandlers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { useRef } from 'react';
import { ICanvasRefMethods } from '@/component/canvas/Canvas.tsx';
import { IMapObject, IMapRefMethods } from '@/component/maps/Map.types.ts';

// TODO: 리팩토룅 시 null을 처리하기
interface IUseEventHandlers {
(
canvasElement: HTMLCanvasElement | null,
canvasRefMethods: ICanvasRefMethods | null,
mapElement: HTMLElement | null,
mapRefMethods: IMapRefMethods | null,
mapObject: IMapObject | null, // 비동기 로딩 시 null로 처리가 될 수 있어서 예외처리 필요
): {
handleClick: (event: React.MouseEvent) => void;
handleMouseDown: (event: React.MouseEvent) => void;
handleMouseMove: (event: React.MouseEvent) => void;
handleMouseUp: (event: React.MouseEvent) => void;
};
}

interface IMouseEventState {
isMouseDown: boolean;
mouseDownPosition: { x: number; y: number };
// mouseMovePosition: { x: number; y: number };
mouseDeltaPosition: { x: number; y: number };
}

const MouseEventStateInitialValue = {
isMouseDown: false,
mouseDownPosition: { x: 0, y: 0 },
// mouseMovePosition: { x: 0, y: 0 },
mouseDeltaPosition: { x: 0, y: 0 },
};

export const useEventHandlers: IUseEventHandlers = (
canvasElement,
canvasRefMethods,
mapElement,
mapRefMethods,
mapObject,
) => {
// if (!canvasElement || !canvasElement || !mapElement || !mapRefMethods || !mapObject)
// throw new Error('🚀 useEventHandler error : null 값이 포함되어 있습니다.');

const mouseEventState = useRef<IMouseEventState>({ ...MouseEventStateInitialValue });

const handleClick = (event: React.MouseEvent) => {
mapRefMethods?.onMouseClickHandler(event);
canvasRefMethods?.onMouseClickHandler(event);
};

const handleMouseDown = (event: React.MouseEvent) => {
if (!mapElement || !canvasElement) return;
mouseEventState.current.isMouseDown = true;
mouseEventState.current.mouseDownPosition = { x: event.clientX, y: event.clientY };
canvasRefMethods?.onMouseDownHandler(event);
};

const handleMouseMove = (event: React.MouseEvent) => {
if (!mapElement || !canvasElement || !mouseEventState.current.isMouseDown) return;

// TODO: 쓰로틀링 걸기
mouseEventState.current.mouseDeltaPosition = {
x: -(event.clientX - mouseEventState.current.mouseDownPosition.x),
y: -(event.clientY - mouseEventState.current.mouseDownPosition.y),
};

// TODO: 범용 지도에 따른 Refactoring 필요, 우선은 네이버 지도에 한해서만 수행
mapObject?.panBy(
new naver.maps.Point(
mouseEventState.current.mouseDeltaPosition.x,
mouseEventState.current.mouseDeltaPosition.y,
),
);

canvasRefMethods?.onMouseMoveHandler(event);
};

const handleMouseUp = (event: React.MouseEvent) => {
if (!mapElement || !canvasElement) return;
mouseEventState.current = { ...MouseEventStateInitialValue };
canvasRefMethods?.onMouseUpHandler(event);
};

return { handleClick, handleMouseDown, handleMouseMove, handleMouseUp };
};
41 changes: 16 additions & 25 deletions frontend/src/component/maps/Map.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,24 @@
import { NaverMap } from '@/component/maps/NaverMap.tsx';
import { ReactNode, useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react';
import { NaverMap } from '@/component/maps/NaverMap.tsx';
import { IMapObject, IMapOptions, IMapRefMethods } from '@/component/maps/Map.types.ts';
import classNames from 'classnames';

type IMapObject = naver.maps.Map | null;

export interface IMapOptions {
lat: number;
lng: number;
zoom?: number;
}
const validateKindOfMap = (type: string) => ['naver'].includes(type);

interface IMapProps extends IMapOptions {
className?: string;
type: string;
initMap: (mapObject: IMapObject) => void;
}

// 부모 컴포넌트가 접근할 수 있는 메서드들을 정의한 인터페이스
export interface IMapRefMethods {
getMapObject: () => naver.maps.Map | null;
getMapContainer: () => HTMLElement | null;
onMouseClickHandler: (event?: React.MouseEvent) => void;
}

const validateKindOfMap = (type: string) => ['naver'].includes(type);

export const Map = forwardRef<IMapRefMethods, IMapProps>((props, ref) => {
if (!validateKindOfMap(props.type)) throw new Error('Invalid map type');
if (!validateKindOfMap(props.type))
throw new Error('🚀 지도 로딩 오류 : 알 수 없는 지도 타입이 인자로 들어 왔습니다.');

const mapRef = useRef<IMapRefMethods | null>(null);
const mapRefMethods = useRef<IMapRefMethods | null>(null);
const mapContainer = useRef<HTMLElement | null>(null);
const [mapObject, setMapObject] = useState<IMapObject>(null);

const [mapObject, setMapObject] = useState<IMapObject>();
const [MapComponent, setMapComponent] = useState<ReactNode>();

const onMapInit = (mapObj: IMapObject) => {
Expand All @@ -44,21 +32,24 @@ export const Map = forwardRef<IMapRefMethods, IMapProps>((props, ref) => {
lat={props.lat}
lng={props.lng}
zoom={props.zoom}
ref={mapRef}
ref={mapRefMethods}
onMapInit={onMapInit}
/>
);
setMapComponent(mapComponent);
}
}, [props.lat, props.lng, props.zoom, props.type]);
}, []);

useEffect(() => {
mapContainer.current = mapRef.current?.getMapContainer() ?? null;
props.initMap(mapObject);
mapContainer.current = mapRefMethods.current?.getMapContainer() ?? null;
if (mapObject) props.initMap(mapObject);
}, [mapObject]);

useImperativeHandle(ref, () => ({
getMapObject: () => mapObject,
getMapObject: () => {
if (mapObject) return mapObject;
throw new Error('🚀 지도 로딩 오류 : 지도 객체가 존재하지 않습니다.');
},
getMapContainer: () => mapContainer.current,
onMouseClickHandler: () => {},
}));
Expand Down
42 changes: 42 additions & 0 deletions frontend/src/component/maps/Map.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export type IMapObject = naver.maps.Map;

export type IMapLatLngBound = naver.maps.LatLngBounds;

export interface IMapOptions {
lat: number;
lng: number;
zoom?: number;
}

/**
* Forward Ref 를 통해서, 부모에서 자식 컴포넌트의 Ref에 접근할 때 쓰이는 인터페이스.
* 다음과 같은 목적으로 쓰인다.
* 1. 지도 컨테이너 요소와, 지도 객체를 가져온다.
* 2. 지도 객체의 이벤트 위임을 위해 자신을 컨트롤 할 수 있는 Handler를 부모에게 전달하는 역할을 한다.
* 이렇게 전달받은 핸들러로 부모 컴포넌트에서 자식에 있는 지도 객체를 컨트롤 할 수 있다.
* */
export interface IMapRefMethods {
getMapObject: () => naver.maps.Map | null;
getMapContainer: () => HTMLElement | null;
onMouseClickHandler: (event?: React.MouseEvent) => void;
}

// lat: 위도(y), lng: 경도(x) INaverMapVertexPosition
export interface IMapVertexCoordinate {
ne: {
lng: number;
lat: number;
};
nw: {
lng: number;
lat: number;
};
se: {
lng: number;
lat: number;
};
sw: {
lng: number;
lat: number;
};
}
25 changes: 16 additions & 9 deletions frontend/src/component/maps/NaverMap.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { setNaverMapSync } from '@/component/maps/naverMapUtils.ts';
import { IMapOptions, IMapRefMethods } from '@/component/maps/Map.tsx';
import { IMapOptions, IMapRefMethods } from '@/component/maps/Map.types.ts';

interface INaverMapProps extends IMapOptions {
onMapInit: (map: naver.maps.Map) => void; // 콜백 프로퍼티 추가
}

export const NaverMap = forwardRef<IMapRefMethods, INaverMapProps>((props, ref) => {
const naverMapObject = useRef<naver.maps.Map | null>(null);
const naverMapContainer = useRef<HTMLElement | null>(null);
const mapObject = useRef<naver.maps.Map | null>(null);
const mapContainer = useRef<HTMLElement | null>(null);

const [mapOptions, setMapOptions] = useState<IMapOptions>({
lat: props.lat,
lng: props.lng,
Expand All @@ -24,17 +25,23 @@ export const NaverMap = forwardRef<IMapRefMethods, INaverMapProps>((props, ref)
}, [props.lat, props.lng, props.zoom]);

useEffect(() => {
if (naverMapContainer.current && mapOptions !== null) {
naverMapObject.current = setNaverMapSync(naverMapContainer.current, mapOptions);
if (naverMapObject.current !== null) props.onMapInit(naverMapObject.current); // 콜백 호출
if (mapContainer.current && mapOptions) {
mapObject.current = setNaverMapSync(mapContainer.current, mapOptions);
if (mapObject.current) props.onMapInit(mapObject.current); // 콜백 호출
}
}, [mapOptions]);

useImperativeHandle(ref, () => ({
getMapObject: () => naverMapObject.current,
getMapContainer: () => naverMapContainer.current,
getMapObject: () => {
if (mapObject) return mapObject.current;
throw new Error('🚀 지도 로딩 오류 : 지도 객체가 존재하지 않습니다.');
},
getMapContainer: () => {
if (mapContainer) return mapContainer.current;
throw new Error('🚀 지도 로딩 오류 : 지도 컨테이너가 존재하지 않습니다.');
},
onMouseClickHandler: () => {},
}));

return <section ref={naverMapContainer} className="h-full w-full" />;
return <section ref={mapContainer} className="h-full w-full" />;
});
Loading
Loading