Skip to content
Open
21 changes: 15 additions & 6 deletions apps/web/src/components/common/BottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,16 @@ export const BottomSheetOverlay = ({ className, ...props }: React.ComponentProps
);
};

export const BottomSheetContent = ({
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) => {
type BottomSheetContentProps = React.ComponentProps<typeof DialogPrimitive.Content> & {
/**
* 스크린 리더에 전달할 숨김 접근성 설명 문구
* 생략하면 설명 없음으로 보고 aria-describedby를 비움
* 화면에 직접 두는 Description이 있으면 null을 넘겨 Radix의 연결을 유지함
*/
ariaDescription?: string | null;
};

export const BottomSheetContent = ({ className, children, ariaDescription, ...props }: BottomSheetContentProps) => {
return (
<BottomSheetPortal>
<BottomSheetOverlay />
Expand All @@ -58,9 +63,13 @@ export const BottomSheetContent = ({
e.preventDefault();
(e.currentTarget as HTMLElement).focus();
}}
// 설명이 없으면 Radix가 기본으로 연결하는 aria-describedby를 끄고 개발 경고도 막음 (null은 직접 둔 Description 연결 유지)
{...(ariaDescription === undefined && { "aria-describedby": undefined })}
{...props}
>
<DialogPrimitive.Description className="sr-only">바텀시트 내용</DialogPrimitive.Description>
{typeof ariaDescription === "string" && (
<DialogPrimitive.Description className="sr-only">{ariaDescription}</DialogPrimitive.Description>
)}
{children}
</DialogPrimitive.Content>
</BottomSheetPortal>
Expand Down
18 changes: 7 additions & 11 deletions apps/web/src/components/common/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,14 @@ export const DialogOverlay = ({ className, ...props }: React.ComponentProps<type

type DialogContentProps = React.ComponentProps<typeof DialogPrimitive.Content> & {
/**
* 보이는 DialogDescription이 없을 때 스크린 리더에 전달되는 접근성 설명입니다.
* 이 텍스트는 시각적으로 숨겨지지만 보조 기술에는 전달됩니다.
* 화면에 DialogDescription을 직접 두는 경우 null을 넘겨 설명 요소(id)가 두 개 생기지 않게 합니다.
* @default "대화상자 내용"
* 스크린 리더에 전달할 숨김 접근성 설명 문구
* 생략하면 설명 없음으로 보고 aria-describedby를 비움
* 화면에 직접 두는 Description이 있으면 null을 넘겨 Radix의 연결을 유지함
*/
ariaDescription?: string | null;
};

export const DialogContent = ({
className,
children,
ariaDescription = "대화상자 내용",
...props
}: DialogContentProps) => {
export const DialogContent = ({ className, children, ariaDescription, ...props }: DialogContentProps) => {
return (
<DialogPortal>
<DialogOverlay className="bg-black/40" />
Expand All @@ -68,9 +62,11 @@ export const DialogContent = ({
e.preventDefault();
(e.currentTarget as HTMLElement).focus();
}}
// 설명이 없으면 Radix가 기본으로 연결하는 aria-describedby를 끄고 개발 경고도 막음 (null은 직접 둔 Description 연결 유지)
{...(ariaDescription === undefined && { "aria-describedby": undefined })}
{...props}
>
{ariaDescription !== null && (
{typeof ariaDescription === "string" && (
<DialogPrimitive.Description className="sr-only">{ariaDescription}</DialogPrimitive.Description>
)}
{children}
Expand Down
13 changes: 9 additions & 4 deletions apps/web/src/components/common/InAppNavigationTracker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,23 @@
import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";

import { markInAppNavigation } from "@/utils/navigation";
import { markCurrentHistoryEntryInApp, markInAppNavigation } from "@/utils/navigation";

/**
* 처음 들어온 화면에서 다른 화면으로 이동하면 앱 안 이동이 있었다고 기록함 (GLB-239)
* 화면 이동이 있으면 앱 안 이동이 있었다고 탭과 현재 history 항목에 기록함 (GLB-239, GLB-259)
* 뒤로가기 버튼이 이 기록으로 이전 화면이 앱 안에 있는지 판단함
*/
export const InAppNavigationTracker = () => {
const pathname = usePathname();
const entryPathnameRef = useRef(pathname);
const previousPathnameRef = useRef(pathname);

useEffect(() => {
if (pathname !== entryPathnameRef.current) markInAppNavigation();
if (pathname === previousPathnameRef.current) return;

previousPathnameRef.current = pathname;
markInAppNavigation();
// 새로 만들어진 history 항목에 표시해, 직접 진입한 항목과 구분함
markCurrentHistoryEntryInApp();
}, [pathname]);

return null;
Expand Down
56 changes: 56 additions & 0 deletions apps/web/src/components/common/dialogAccessibility.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// @vitest-environment jsdom
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";

import { afterEach, describe, expect, it, vi } from "vitest";

import { BottomSheet, BottomSheetContent, BottomSheetTitle } from "./BottomSheet";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "./Dialog";

afterEach(() => vi.unstubAllGlobals());

describe.each([
{ name: "Dialog", Root: Dialog, Content: DialogContent, Title: DialogTitle },
{ name: "BottomSheet", Root: BottomSheet, Content: BottomSheetContent, Title: BottomSheetTitle },
])("$name 접근성 설명", ({ Root, Content, Title }) => {
it.each([undefined, null, "기록 삭제 확인"])("설명 %s의 연결을 처리함", async ariaDescription => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
try {
await act(async () =>
root.render(
createElement(
Root,
{ open: true },
createElement(
Content,
ariaDescription === undefined ? {} : { ariaDescription },
createElement(Title, null, "제목"),
ariaDescription === null ? createElement(DialogDescription, null, "직접 작성한 설명") : null
)
)
)
);
const dialog = document.querySelector('[role="dialog"]');
expect(dialog).not.toBeNull();
if (ariaDescription === undefined) {
expect(dialog?.hasAttribute("aria-describedby")).toBe(false);
expect(dialog?.querySelector("p")).toBeNull();
} else {
const id = dialog?.getAttribute("aria-describedby");
expect(id).toBeTruthy();
expect(document.getElementById(id!)?.textContent).toBe(ariaDescription ?? "직접 작성한 설명");
if (ariaDescription === null) {
const description = dialog?.querySelector('[data-slot="dialog-description"]');
expect(description?.id).toBe(id);
expect(dialog?.querySelectorAll("p")).toHaveLength(1);
}
}
} finally {
await act(async () => root.unmount());
container.remove();
}
});
});
7 changes: 5 additions & 2 deletions apps/web/src/components/imageMetadata/ImageMetadata.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { sendGAEvent } from "@next/third-parties/google";

import { cn } from "@/utils/cn";
import { getAuthInfo } from "@/utils/cookies";
import { isCurrentHistoryEntryInApp } from "@/utils/navigation";

import { Header } from "../common/Header";
import { CityErrorFallback } from "./CityErrorFallback";
Expand Down Expand Up @@ -144,9 +145,11 @@ export const ImageMetadataComponent = ({

const leave = () => {
allowLeaveRef.current = true;
// history.length에는 앞으로 가기 항목도 포함되므로 실제 뒤로 갈 수 있는지를 확인한다
// history.length에는 앞으로 가기 항목도 포함되므로 Navigation API로 실제 뒤로 갈 수 있는지 확인함
// Navigation API가 없는 브라우저(구버전 iOS Safari 등)는 현재 history 항목이 앱 안 이동으로 만들어졌는지로 직접 진입 여부를 판단함
const navigation = (window as Window & { navigation?: { canGoBack: boolean } }).navigation;
if (navigation?.canGoBack) {
const canGoBack = navigation ? navigation.canGoBack : isCurrentHistoryEntryInApp();
if (canGoBack) {
router.back();
return;
}
Expand Down
9 changes: 0 additions & 9 deletions apps/web/src/components/record/EditClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -327,9 +327,6 @@ export const EditClient = ({ cities, deletedCities = [] }: EditClientProps) => {
.filter(([id]) => !currentIds.has(id))
.map(([, city]) => city);

console.log(`[Save] 추가할 도시:`, addedCities);
console.log(`[Save] 삭제할 도시:`, deletedCities);

// 추가된 도시들을 City 타입으로 변환 (배열로 한번에 전송)
const citiesToAdd: City[] = addedCities.map(city => ({
id: city.id,
Expand All @@ -344,19 +341,15 @@ export const EditClient = ({ cities, deletedCities = [] }: EditClientProps) => {
// 삭제된 도시들은 여행지 조회 응답의 cityId로 삭제 요청 (id도 String(cityId)로 만들어짐)
const deletePromises = deletedCities.map(city => {
const cityId = city.cityId ?? Number(city.id);
console.log(`[Save] 도시 삭제 요청:`, cityId);
return deleteMemberTravel({ cityId, token });
});

// 추가 요청 (배열로 한번에 전송)
let addPromise: Promise<CreateTravelRecordsResponse> | null = null;
if (citiesToAdd.length > 0) {
console.log(`[Save] 도시 추가 요청:`, citiesToAdd);
addPromise = createMemberTravels({ cities: citiesToAdd });
}

console.log(`[Save] 총 ${citiesToAdd.length}개 추가, ${deletePromises.length}개 삭제 요청 시작`);

// 모든 API 호출 실행
const promises: Promise<unknown>[] = [...deletePromises];
if (addPromise) {
Expand All @@ -365,8 +358,6 @@ export const EditClient = ({ cities, deletedCities = [] }: EditClientProps) => {
await Promise.all(promises);
hasSavedRef.current = true;

console.log(`[Save] 모든 요청 성공`);

// 최소 1.3초 동안 로딩 표시 보장
const elapsedTime = Date.now() - startTime;
const remainingTime = Math.max(0, minLoadingDuration - elapsedTime);
Expand Down
19 changes: 14 additions & 5 deletions apps/web/src/hooks/useClustering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type { CountryData } from "@globber/shared/types/travelPatterns";
import { logger } from "@globber/shared/utils/logger";

import { clusterLocations } from "@/lib/globe/clustering/clusteringAlgorithm";
import { reuseClusters } from "@/lib/globe/clustering/reuseClusters";
import {
createClusterTransitionHandler,
createGlobeRotationHandler,
Expand Down Expand Up @@ -80,6 +81,8 @@ export const useClustering = ({
const [cameraRevision, setCameraRevision] = useState(0);
const cameraTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const cameraPositionRef = useRef<{ lat: number; lng: number } | null>(null);
// 마지막으로 커밋된 클러스터 결과를 보관해 내용이 같으면 같은 객체·배열을 돌려줌
const committedClustersRef = useRef<ClusterData[]>([]);
// 회전 좌표는 ref에 보관하고 클러스터 재계산만 100ms 단위로 알린다.
// 매 프레임 상태를 바꿔 회전이 끊기는 것을 피하면서 마지막 화면 좌표를 반영한다.
const lastRotationRef = useRef<{ lat: number; lng: number }>({ lat: 0, lng: 0 });
Expand Down Expand Up @@ -124,12 +127,12 @@ export const useClustering = ({
* @responsibility 줌 레벨, 모드, 선택 상태에 따라 최적의 클러스터링 수행
*/
const clusteredData = useMemo(() => {
let next: ClusterData[] = [];

try {
const dataToCluster = selectedClusterData && selectedClusterData.length > 0 ? selectedClusterData : countries;

if (!dataToCluster || dataToCluster.length === 0) return [];

return clusterLocations(
next = clusterLocations(
dataToCluster,
globeRef,
mode,
Expand All @@ -139,9 +142,10 @@ export const useClustering = ({
);
} catch (error) {
logger.error("Clustering calculation failed:", error);

return [];
}

// 빈 결과와 오류 결과도 같은 경로를 거쳐 이전 배열을 재사용함
return reuseClusters(committedClustersRef.current, next);
// eslint-disable-next-line react-hooks/exhaustive-deps -- zoomLevel은 함수 본문에서 직접 참조되지 않지만, 내부의 globeRef.current.getScreenCoords()가 줌/카메라 상태에 따라 다른 화면 좌표를 반환하므로 줌 변경 시마다 재계산을 트리거하기 위해 필요
}, [
countries,
Expand All @@ -155,6 +159,11 @@ export const useClustering = ({
expandedContinentCountryIds,
]);

// 렌더가 폐기돼도 재사용 기준이 바뀌지 않도록 커밋된 뒤에만 기록함
useEffect(() => {
committedClustersRef.current = clusteredData;
}, [clusteredData]);

/**
* 화면에 표시할 클러스터 아이템 (캐싱)
*/
Expand Down
59 changes: 59 additions & 0 deletions apps/web/src/hooks/useClusteringReuse.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { act, createElement, useLayoutEffect } from "react";
import { createRoot } from "react-dom/client";

import type { GlobeInstance } from "globe.gl";
import { JSDOM } from "jsdom";
import { afterEach, describe, expect, it, vi } from "vitest";

import { useClustering } from "./useClustering";

describe("회전 중 클러스터 참조 유지", () => {
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});

it("화면 좌표가 바뀌어도 같은 클러스터의 배열과 객체를 재사용함", async () => {
vi.useFakeTimers();
const dom = new JSDOM();
vi.stubGlobal("window", dom.window);
vi.stubGlobal("document", dom.window.document);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
let separation = 500;
const getScreenCoords = vi.fn((_lat: number, lng: number) => ({ x: lng * separation, y: 0 }));
const globeRef = { current: { getScreenCoords } as unknown as GlobeInstance };
const countries = [
{ id: "FRA", name: "파리", lat: 48, lng: 2, flag: "🇫🇷", color: "blue" },
{ id: "BEL", name: "브뤼셀", lat: 50, lng: 4, flag: "🇧🇪", color: "blue" },
];
let result: ReturnType<typeof useClustering>;
const onSelectedDataChange = vi.fn();
const onSnapZoomChange = vi.fn();
const Harness = () => {
const clustering = useClustering({ countries, globeRef, zoomLevel: 2, onSelectedDataChange, onSnapZoomChange });
useLayoutEffect(() => {
result = clustering;
});
return null;
};
const root = createRoot(dom.window.document.createElement("div"));
await act(async () => root.render(createElement(Harness)));
expect(result!.visibleItems).toHaveLength(2);
const previous = result!.visibleItems;
const callsBeforeRotation = getScreenCoords.mock.calls.length;
await act(async () => {
result!.handleGlobeRotation(0, 5);
separation = 600;
result!.handleGlobeRotation(0, 10);
vi.advanceTimersByTime(99);
});
expect(getScreenCoords).toHaveBeenCalledTimes(callsBeforeRotation);
await act(async () => {
vi.advanceTimersByTime(1);
});
expect(getScreenCoords).toHaveBeenCalledTimes(callsBeforeRotation + 3);
expect(result!.visibleItems).toBe(previous);
expect(result!.visibleItems[0]).toBe(previous[0]);
await act(async () => root.unmount());
});
});
Loading
Loading