From 2ff06197dafc23170a9b82ea3589b21117c6b416 Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 09:10:48 +0900 Subject: [PATCH 1/6] =?UTF-8?q?fix(globe):=20=ED=81=B4=EB=9F=AC=EC=8A=A4?= =?UTF-8?q?=ED=84=B0=20=EA=B2=B0=EA=B3=BC=EA=B0=80=20=EA=B0=99=EC=9C=BC?= =?UTF-8?q?=EB=A9=B4=20=EC=9D=B4=EC=A0=84=20=EA=B0=9D=EC=B2=B4=EC=99=80=20?= =?UTF-8?q?=EB=B0=B0=EC=97=B4=EC=9D=84=20=EC=9E=AC=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=ED=95=B4=20=EB=9D=BC=EB=B2=A8=20=EC=9E=AC=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EB=B0=A9=EC=A7=80=20(GLB-205,=20GLB-231)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - three-globe는 객체 참조로 같은 데이터인지 판단하므로 줌·회전 재계산마다 라벨이 다시 만들어졌음 - 화면 계산 필드와 three-globe가 붙이는 __threeObjHtml은 비교에서 제외 --- apps/web/src/hooks/useClustering.ts | 17 ++-- apps/web/src/hooks/useClusteringReuse.test.ts | 59 +++++++++++++ .../globe/clustering/reuseClusters.test.ts | 88 +++++++++++++++++++ .../src/lib/globe/clustering/reuseClusters.ts | 56 ++++++++++++ 4 files changed, 215 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/hooks/useClusteringReuse.test.ts create mode 100644 apps/web/src/lib/globe/clustering/reuseClusters.test.ts create mode 100644 apps/web/src/lib/globe/clustering/reuseClusters.ts diff --git a/apps/web/src/hooks/useClustering.ts b/apps/web/src/hooks/useClustering.ts index ed877e90..9744a1ac 100644 --- a/apps/web/src/hooks/useClustering.ts +++ b/apps/web/src/hooks/useClustering.ts @@ -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, @@ -80,6 +81,8 @@ export const useClustering = ({ const [cameraRevision, setCameraRevision] = useState(0); const cameraTimerRef = useRef | null>(null); const cameraPositionRef = useRef<{ lat: number; lng: number } | null>(null); + // 직전 클러스터 결과를 보관해 내용이 같으면 같은 객체·배열을 돌려줌 + const previousClustersRef = useRef([]); // 회전 좌표는 ref에 보관하고 클러스터 재계산만 100ms 단위로 알린다. // 매 프레임 상태를 바꿔 회전이 끊기는 것을 피하면서 마지막 화면 좌표를 반영한다. const lastRotationRef = useRef<{ lat: number; lng: number }>({ lat: 0, lng: 0 }); @@ -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, @@ -139,9 +142,13 @@ export const useClustering = ({ ); } catch (error) { logger.error("Clustering calculation failed:", error); - - return []; } + + // 빈 결과와 오류 결과도 같은 경로를 거쳐 이전 배열을 재사용함 + const clusters = reuseClusters(previousClustersRef.current, next); + previousClustersRef.current = clusters; + + return clusters; // eslint-disable-next-line react-hooks/exhaustive-deps -- zoomLevel은 함수 본문에서 직접 참조되지 않지만, 내부의 globeRef.current.getScreenCoords()가 줌/카메라 상태에 따라 다른 화면 좌표를 반환하므로 줌 변경 시마다 재계산을 트리거하기 위해 필요 }, [ countries, diff --git a/apps/web/src/hooks/useClusteringReuse.test.ts b/apps/web/src/hooks/useClusteringReuse.test.ts new file mode 100644 index 00000000..e9706cb0 --- /dev/null +++ b/apps/web/src/hooks/useClusteringReuse.test.ts @@ -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; + 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()); + }); +}); diff --git a/apps/web/src/lib/globe/clustering/reuseClusters.test.ts b/apps/web/src/lib/globe/clustering/reuseClusters.test.ts new file mode 100644 index 00000000..3526f96b --- /dev/null +++ b/apps/web/src/lib/globe/clustering/reuseClusters.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from "vitest"; + +import type { ClusterData } from "@/types/clustering"; + +import { reuseClusters } from "./reuseClusters"; + +const city = { id: "KOR", cityId: 1, name: "서울", lat: 37, lng: 127, flag: "🇰🇷", color: "blue" }; + +const makeCluster = (overrides: Partial = {}): ClusterData => ({ + id: "country_KOR", + name: "한국", + flag: "🇰🇷", + lat: 37, + lng: 127, + color: "blue", + items: [city], + count: 1, + clusterType: "country_cluster", + ...overrides, +}); + +it("내용이 모두 같으면 이전 배열을 그대로 돌려준다", () => { + const previous = [makeCluster()]; + const next = [makeCluster({ items: [city] })]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); + +it("화면 계산용 필드만 다르면 같은 내용으로 본다", () => { + const previous = [{ ...makeCluster(), screenPos: { x: 1, y: 2 }, width: 10, effectiveWidth: 5 }]; + const next = [{ ...makeCluster(), screenPos: { x: 3, y: 4 }, width: 12, effectiveWidth: 6 }]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); + +it("일부만 바뀌면 같은 클러스터 객체만 재사용하고 새 배열을 돌려준다", () => { + const unchanged = makeCluster(); + const previous = [unchanged, makeCluster({ id: "country_JPN", name: "일본" })]; + const next = [makeCluster(), makeCluster({ id: "country_JPN", name: "일본", lat: 36 })]; + + const result = reuseClusters(previous, next); + + expect(result).not.toBe(previous); + expect(result[0]).toBe(unchanged); + expect(result[1]).toBe(next[1]); +}); + +it("개수나 순서가 달라지면 새 배열을 돌려준다", () => { + const a = makeCluster(); + const b = makeCluster({ id: "country_JPN", name: "일본" }); + + expect(reuseClusters([a, b], [b, a])).not.toEqual([a, b]); + expect(reuseClusters([a, b], [makeCluster()])).toHaveLength(1); +}); + +it("items 내용이 같으면 새 객체여도 같은 내용으로 본다", () => { + const previous = [makeCluster()]; + const next = [makeCluster({ items: [{ ...city }] })]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); + +it("items 내용이 바뀌면 다른 내용으로 본다", () => { + const previous = [makeCluster()]; + const next = [makeCluster({ items: [{ ...city, name: "부산" }] })]; + + expect(reuseClusters(previous, next)[0]).toBe(next[0]); +}); + +it("three-globe가 붙이는 __threeObjHtml 필드가 있어도 같은 내용으로 본다", () => { + const previous = [{ ...makeCluster(), __threeObjHtml: {} }]; + const next = [makeCluster()]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); + +it("빈 배열은 이전 빈 배열을 그대로 돌려준다", () => { + const previous: ClusterData[] = []; + + expect(reuseClusters(previous, [])).toBe(previous); +}); + +it("NaN 좌표가 반복돼도 같은 내용으로 본다", () => { + const previous = [makeCluster({ lat: Number.NaN })]; + const next = [makeCluster({ lat: Number.NaN })]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); diff --git a/apps/web/src/lib/globe/clustering/reuseClusters.ts b/apps/web/src/lib/globe/clustering/reuseClusters.ts new file mode 100644 index 00000000..ea594481 --- /dev/null +++ b/apps/web/src/lib/globe/clustering/reuseClusters.ts @@ -0,0 +1,56 @@ +import type { ClusterData } from "@/types/clustering"; + +// 내용 비교에 쓰는 도메인 필드 목록 +// three-globe가 데이터 객체에 붙이는 __threeObjHtml 같은 렌더러 필드와 screenPos 같은 화면 계산 필드는 비교에서 제외함 +const CONTENT_KEYS = [ + "id", + "name", + "flag", + "lat", + "lng", + "color", + "count", + "clusterType", + "isExpanded", + "hasRecords", + "thumbnailUrl", + "recordCount", +] as const satisfies readonly (keyof ClusterData)[]; + +const isSameItem = (a: unknown, b: unknown): boolean => { + if (Object.is(a, b)) return true; + if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false; + + const aRecord = a as Record; + const bRecord = b as Record; + const keys = Object.keys(aRecord); + + return keys.length === Object.keys(bRecord).length && keys.every(key => Object.is(aRecord[key], bRecord[key])); +}; + +const isSameCluster = (a: ClusterData, b: ClusterData): boolean => + CONTENT_KEYS.every(key => Object.is(a[key], b[key])) && + a.items.length === b.items.length && + a.items.every((item, index) => isSameItem(item, b.items[index])); + +/** + * 이전 클러스터 결과와 내용이 같으면 이전 객체와 배열을 그대로 재사용함 + * three-globe는 객체 참조로 같은 데이터인지 판단하므로, 참조가 바뀌면 라벨 DOM이 떼어졌다 다시 붙음 + * @param previous - 직전 계산 결과 + * @param next - 새로 계산한 결과 + * @returns 모두 같으면 previous, 일부만 같으면 같은 클러스터는 이전 객체를 쓴 새 배열 + */ +export const reuseClusters = (previous: ClusterData[], next: ClusterData[]): ClusterData[] => { + const previousById = new Map(previous.map(cluster => [cluster.id, cluster])); + + const merged = next.map(cluster => { + const old = previousById.get(cluster.id); + + return old && isSameCluster(old, cluster) ? old : cluster; + }); + + const isSameArray = + merged.length === previous.length && merged.every((cluster, index) => cluster === previous[index]); + + return isSameArray ? previous : merged; +}; From 019419f3d03d69a42cbf87cff3ab8166f4ce7459 Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 09:11:04 +0900 Subject: [PATCH 2/6] =?UTF-8?q?fix(image-metadata):=20Navigation=20API?= =?UTF-8?q?=EA=B0=80=20=EC=97=86=EB=8A=94=20=EB=B8=8C=EB=9D=BC=EC=9A=B0?= =?UTF-8?q?=EC=A0=80=EC=97=90=EC=84=9C=EB=8F=84=20=EC=95=B1=20=EC=95=88?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=93=A4=EC=96=B4=EC=98=A8=20=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=20=EB=92=A4=EB=A1=9C=EA=B0=80=EA=B8=B0=20=EC=A0=95?= =?UTF-8?q?=EC=83=81=ED=99=94=20(GLB-259)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Navigation API가 없으면 기존 앱 안 이동 기록으로 직접 진입 여부를 판단 --- apps/web/src/components/imageMetadata/ImageMetadata.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/imageMetadata/ImageMetadata.tsx b/apps/web/src/components/imageMetadata/ImageMetadata.tsx index 73f1bc8e..2b736eff 100644 --- a/apps/web/src/components/imageMetadata/ImageMetadata.tsx +++ b/apps/web/src/components/imageMetadata/ImageMetadata.tsx @@ -7,6 +7,7 @@ import { sendGAEvent } from "@next/third-parties/google"; import { cn } from "@/utils/cn"; import { getAuthInfo } from "@/utils/cookies"; +import { hasInAppNavigation } from "@/utils/navigation"; import { Header } from "../common/Header"; import { CityErrorFallback } from "./CityErrorFallback"; @@ -144,9 +145,11 @@ export const ImageMetadataComponent = ({ const leave = () => { allowLeaveRef.current = true; - // history.length에는 앞으로 가기 항목도 포함되므로 실제 뒤로 갈 수 있는지를 확인한다 + // history.length에는 앞으로 가기 항목도 포함되므로 Navigation API로 실제 뒤로 갈 수 있는지 확인함 + // Navigation API가 없는 브라우저(구버전 iOS Safari 등)는 앱 안 이동 기록으로 직접 진입 여부를 판단함 const navigation = (window as Window & { navigation?: { canGoBack: boolean } }).navigation; - if (navigation?.canGoBack) { + const canGoBack = navigation ? navigation.canGoBack : hasInAppNavigation(); + if (canGoBack) { router.back(); return; } From e7bc0648bf989f8cfdc17730f0c05495a49c5b5c Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 09:11:13 +0900 Subject: [PATCH 3/6] =?UTF-8?q?fix:=20=EB=8F=84=EC=8B=9C=20=ED=8E=B8?= =?UTF-8?q?=EC=A7=91=20=EC=A0=80=EC=9E=A5=20=EB=A1=9C=EA=B7=B8=EC=99=80=20?= =?UTF-8?q?=EC=A2=8C=ED=91=9C=20=EB=A1=9C=EA=B7=B8=20=EC=A0=9C=EA=B1=B0=20?= =?UTF-8?q?(GLB-128)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 운영에서 추가·삭제 도시 목록과 cityId, 위도·경도가 콘솔에 남던 것을 제거 --- apps/web/src/components/record/EditClient.tsx | 9 --------- apps/web/src/utils/geocoding.ts | 1 - 2 files changed, 10 deletions(-) diff --git a/apps/web/src/components/record/EditClient.tsx b/apps/web/src/components/record/EditClient.tsx index 1f7c3b80..289df458 100644 --- a/apps/web/src/components/record/EditClient.tsx +++ b/apps/web/src/components/record/EditClient.tsx @@ -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, @@ -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 | 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[] = [...deletePromises]; if (addPromise) { @@ -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); diff --git a/apps/web/src/utils/geocoding.ts b/apps/web/src/utils/geocoding.ts index 47dfd553..bfc6490a 100644 --- a/apps/web/src/utils/geocoding.ts +++ b/apps/web/src/utils/geocoding.ts @@ -49,7 +49,6 @@ export const reverseGeocode = async (latitude: number, longitude: number): Promi const geocodeData = await geocodeResponse.json(); if (!geocodeData.results || geocodeData.results.length === 0) { - console.warn("No geocoding results found for coordinates:", latitude, longitude); return null; } From c623c4d1f94514066d897bceb0e48cc6c0dfe561 Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 09:11:30 +0900 Subject: [PATCH 4/6] =?UTF-8?q?fix(a11y):=20=EB=8C=80=ED=99=94=EC=83=81?= =?UTF-8?q?=EC=9E=90=C2=B7=EB=B0=94=ED=85=80=EC=8B=9C=ED=8A=B8=EC=9D=98=20?= =?UTF-8?q?=EA=B8=B0=EB=B3=B8=20=EC=84=A4=EB=AA=85=EC=9D=84=20=EC=97=86?= =?UTF-8?q?=EC=95=A0=EA=B3=A0=20=ED=95=84=EC=9A=94=ED=95=9C=20=EA=B3=B3?= =?UTF-8?q?=EB=A7=8C=20=EC=A7=80=EC=A0=95=20(GLB-328)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - BottomSheetContent에 ariaDescription 추가, 생략하면 설명 없음으로 두고 null이면 직접 둔 Description 연결 유지 --- .../web/src/components/common/BottomSheet.tsx | 21 +++++-- apps/web/src/components/common/Dialog.tsx | 18 +++--- .../common/dialogAccessibility.test.ts | 56 +++++++++++++++++++ 3 files changed, 78 insertions(+), 17 deletions(-) create mode 100644 apps/web/src/components/common/dialogAccessibility.test.ts diff --git a/apps/web/src/components/common/BottomSheet.tsx b/apps/web/src/components/common/BottomSheet.tsx index 3cd030f2..5d3e9bee 100644 --- a/apps/web/src/components/common/BottomSheet.tsx +++ b/apps/web/src/components/common/BottomSheet.tsx @@ -34,11 +34,16 @@ export const BottomSheetOverlay = ({ className, ...props }: React.ComponentProps ); }; -export const BottomSheetContent = ({ - className, - children, - ...props -}: React.ComponentProps) => { +type BottomSheetContentProps = React.ComponentProps & { + /** + * 스크린 리더에 전달할 숨김 접근성 설명 문구 + * 생략하면 설명 없음으로 보고 aria-describedby를 비움 + * 화면에 직접 두는 Description이 있으면 null을 넘겨 Radix의 연결을 유지함 + */ + ariaDescription?: string | null; +}; + +export const BottomSheetContent = ({ className, children, ariaDescription, ...props }: BottomSheetContentProps) => { return ( @@ -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} > - 바텀시트 내용 + {typeof ariaDescription === "string" && ( + {ariaDescription} + )} {children} diff --git a/apps/web/src/components/common/Dialog.tsx b/apps/web/src/components/common/Dialog.tsx index 69d25b7f..f7d15c10 100644 --- a/apps/web/src/components/common/Dialog.tsx +++ b/apps/web/src/components/common/Dialog.tsx @@ -36,20 +36,14 @@ export const DialogOverlay = ({ className, ...props }: React.ComponentProps & { /** - * 보이는 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 ( @@ -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" && ( {ariaDescription} )} {children} diff --git a/apps/web/src/components/common/dialogAccessibility.test.ts b/apps/web/src/components/common/dialogAccessibility.test.ts new file mode 100644 index 00000000..ff6b4586 --- /dev/null +++ b/apps/web/src/components/common/dialogAccessibility.test.ts @@ -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(); + } + }); +}); From 7f1e4e14606011e52078e1426638bf455b21b9e8 Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 15:09:11 +0900 Subject: [PATCH 5/6] =?UTF-8?q?fix(globe):=20=ED=81=B4=EB=9F=AC=EC=8A=A4?= =?UTF-8?q?=ED=84=B0=20=EC=9E=AC=EC=82=AC=EC=9A=A9=20=EC=BA=90=EC=8B=9C?= =?UTF-8?q?=EB=A5=BC=20=EC=BB=A4=EB=B0=8B=20=ED=9B=84=EC=97=90=20=EA=B8=B0?= =?UTF-8?q?=EB=A1=9D=ED=95=98=EA=B3=A0=20thumbnails=EB=A5=BC=20=EA=B0=92?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EB=B9=84=EA=B5=90=20(GLB-205)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 렌더 중 ref 쓰기를 effect로 옮겨 폐기된 렌더가 재사용 기준을 바꾸지 않게 함 - thumbnails 배열은 길이와 각 문자열로 비교 --- apps/web/src/hooks/useClustering.ts | 14 ++++++++------ .../src/lib/globe/clustering/reuseClusters.test.ts | 14 ++++++++++++++ apps/web/src/lib/globe/clustering/reuseClusters.ts | 10 +++++++++- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/apps/web/src/hooks/useClustering.ts b/apps/web/src/hooks/useClustering.ts index 9744a1ac..2c9f01b3 100644 --- a/apps/web/src/hooks/useClustering.ts +++ b/apps/web/src/hooks/useClustering.ts @@ -81,8 +81,8 @@ export const useClustering = ({ const [cameraRevision, setCameraRevision] = useState(0); const cameraTimerRef = useRef | null>(null); const cameraPositionRef = useRef<{ lat: number; lng: number } | null>(null); - // 직전 클러스터 결과를 보관해 내용이 같으면 같은 객체·배열을 돌려줌 - const previousClustersRef = useRef([]); + // 마지막으로 커밋된 클러스터 결과를 보관해 내용이 같으면 같은 객체·배열을 돌려줌 + const committedClustersRef = useRef([]); // 회전 좌표는 ref에 보관하고 클러스터 재계산만 100ms 단위로 알린다. // 매 프레임 상태를 바꿔 회전이 끊기는 것을 피하면서 마지막 화면 좌표를 반영한다. const lastRotationRef = useRef<{ lat: number; lng: number }>({ lat: 0, lng: 0 }); @@ -145,10 +145,7 @@ export const useClustering = ({ } // 빈 결과와 오류 결과도 같은 경로를 거쳐 이전 배열을 재사용함 - const clusters = reuseClusters(previousClustersRef.current, next); - previousClustersRef.current = clusters; - - return clusters; + return reuseClusters(committedClustersRef.current, next); // eslint-disable-next-line react-hooks/exhaustive-deps -- zoomLevel은 함수 본문에서 직접 참조되지 않지만, 내부의 globeRef.current.getScreenCoords()가 줌/카메라 상태에 따라 다른 화면 좌표를 반환하므로 줌 변경 시마다 재계산을 트리거하기 위해 필요 }, [ countries, @@ -162,6 +159,11 @@ export const useClustering = ({ expandedContinentCountryIds, ]); + // 렌더가 폐기돼도 재사용 기준이 바뀌지 않도록 커밋된 뒤에만 기록함 + useEffect(() => { + committedClustersRef.current = clusteredData; + }, [clusteredData]); + /** * 화면에 표시할 클러스터 아이템 (캐싱) */ diff --git a/apps/web/src/lib/globe/clustering/reuseClusters.test.ts b/apps/web/src/lib/globe/clustering/reuseClusters.test.ts index 3526f96b..c289652b 100644 --- a/apps/web/src/lib/globe/clustering/reuseClusters.test.ts +++ b/apps/web/src/lib/globe/clustering/reuseClusters.test.ts @@ -86,3 +86,17 @@ it("NaN 좌표가 반복돼도 같은 내용으로 본다", () => { expect(reuseClusters(previous, next)).toBe(previous); }); + +it("thumbnails 배열은 서로 다른 배열이어도 같은 문자열이면 같은 내용으로 본다", () => { + const previous = [makeCluster({ items: [{ ...city, thumbnails: ["a.jpg", "b.jpg"] }] })]; + const next = [makeCluster({ items: [{ ...city, thumbnails: ["a.jpg", "b.jpg"] }] })]; + + expect(reuseClusters(previous, next)).toBe(previous); +}); + +it("thumbnails 문자열이 다르면 다른 내용으로 본다", () => { + const previous = [makeCluster({ items: [{ ...city, thumbnails: ["a.jpg"] }] })]; + const next = [makeCluster({ items: [{ ...city, thumbnails: ["c.jpg"] }] })]; + + expect(reuseClusters(previous, next)[0]).toBe(next[0]); +}); diff --git a/apps/web/src/lib/globe/clustering/reuseClusters.ts b/apps/web/src/lib/globe/clustering/reuseClusters.ts index ea594481..82e99984 100644 --- a/apps/web/src/lib/globe/clustering/reuseClusters.ts +++ b/apps/web/src/lib/globe/clustering/reuseClusters.ts @@ -17,6 +17,14 @@ const CONTENT_KEYS = [ "recordCount", ] as const satisfies readonly (keyof ClusterData)[]; +// thumbnails 같은 문자열 배열은 참조가 아니라 길이와 각 값으로 비교함 +const isSameValue = (a: unknown, b: unknown): boolean => { + if (Object.is(a, b)) return true; + if (!Array.isArray(a) || !Array.isArray(b)) return false; + + return a.length === b.length && a.every((value, index) => Object.is(value, b[index])); +}; + const isSameItem = (a: unknown, b: unknown): boolean => { if (Object.is(a, b)) return true; if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false; @@ -25,7 +33,7 @@ const isSameItem = (a: unknown, b: unknown): boolean => { const bRecord = b as Record; const keys = Object.keys(aRecord); - return keys.length === Object.keys(bRecord).length && keys.every(key => Object.is(aRecord[key], bRecord[key])); + return keys.length === Object.keys(bRecord).length && keys.every(key => isSameValue(aRecord[key], bRecord[key])); }; const isSameCluster = (a: ClusterData, b: ClusterData): boolean => From 498f17dc0990f91e99fb5d579bdd543b73bad6ab Mon Sep 17 00:00:00 2001 From: jiohjung98 Date: Mon, 16 Nov 2026 15:09:22 +0900 Subject: [PATCH 6/6] =?UTF-8?q?fix(image-metadata):=20=EB=92=A4=EB=A1=9C?= =?UTF-8?q?=EA=B0=80=EA=B8=B0=20=ED=8C=90=EB=8B=A8=EC=9D=84=20=ED=83=AD=20?= =?UTF-8?q?=EC=A0=84=EC=B2=B4=EA=B0=80=20=EC=95=84=EB=8B=8C=20=ED=98=84?= =?UTF-8?q?=EC=9E=AC=20history=20=ED=95=AD=EB=AA=A9=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EB=B3=80=EA=B2=BD=20(GLB-259)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 앱 안 이동으로 만들어진 history 항목에 표시를 남겨, 이전에 이동한 탭에서 직접 연 화면도 대체 경로로 보냄 --- .../common/InAppNavigationTracker.tsx | 13 +++-- .../imageMetadata/ImageMetadata.tsx | 6 +-- apps/web/src/utils/navigation.test.ts | 54 ++++++++++++++++++- apps/web/src/utils/navigation.ts | 27 ++++++++++ 4 files changed, 92 insertions(+), 8 deletions(-) diff --git a/apps/web/src/components/common/InAppNavigationTracker.tsx b/apps/web/src/components/common/InAppNavigationTracker.tsx index 08e1d781..70b7df0c 100644 --- a/apps/web/src/components/common/InAppNavigationTracker.tsx +++ b/apps/web/src/components/common/InAppNavigationTracker.tsx @@ -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; diff --git a/apps/web/src/components/imageMetadata/ImageMetadata.tsx b/apps/web/src/components/imageMetadata/ImageMetadata.tsx index 2b736eff..e833b5eb 100644 --- a/apps/web/src/components/imageMetadata/ImageMetadata.tsx +++ b/apps/web/src/components/imageMetadata/ImageMetadata.tsx @@ -7,7 +7,7 @@ import { sendGAEvent } from "@next/third-parties/google"; import { cn } from "@/utils/cn"; import { getAuthInfo } from "@/utils/cookies"; -import { hasInAppNavigation } from "@/utils/navigation"; +import { isCurrentHistoryEntryInApp } from "@/utils/navigation"; import { Header } from "../common/Header"; import { CityErrorFallback } from "./CityErrorFallback"; @@ -146,9 +146,9 @@ export const ImageMetadataComponent = ({ const leave = () => { allowLeaveRef.current = true; // history.length에는 앞으로 가기 항목도 포함되므로 Navigation API로 실제 뒤로 갈 수 있는지 확인함 - // Navigation API가 없는 브라우저(구버전 iOS Safari 등)는 앱 안 이동 기록으로 직접 진입 여부를 판단함 + // Navigation API가 없는 브라우저(구버전 iOS Safari 등)는 현재 history 항목이 앱 안 이동으로 만들어졌는지로 직접 진입 여부를 판단함 const navigation = (window as Window & { navigation?: { canGoBack: boolean } }).navigation; - const canGoBack = navigation ? navigation.canGoBack : hasInAppNavigation(); + const canGoBack = navigation ? navigation.canGoBack : isCurrentHistoryEntryInApp(); if (canGoBack) { router.back(); return; diff --git a/apps/web/src/utils/navigation.test.ts b/apps/web/src/utils/navigation.test.ts index 21872b8e..ade2bbf9 100644 --- a/apps/web/src/utils/navigation.test.ts +++ b/apps/web/src/utils/navigation.test.ts @@ -1,6 +1,12 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { goBackOrFallback, hasInAppNavigation, markInAppNavigation } from "./navigation"; +import { + goBackOrFallback, + hasInAppNavigation, + isCurrentHistoryEntryInApp, + markCurrentHistoryEntryInApp, + markInAppNavigation, +} from "./navigation"; const createRouter = () => ({ back: vi.fn(), push: vi.fn() }); @@ -60,3 +66,49 @@ describe("goBackOrFallback", () => { expect(router.push).toHaveBeenCalledWith("/"); }); }); + +describe("현재 history 항목 표시", () => { + const stubHistory = (initialState: unknown) => { + const history = { + state: initialState, + replaceState: vi.fn((state: unknown) => { + history.state = state; + }), + }; + vi.stubGlobal("window", { history }); + + return history; + }; + + it("표시하지 않은 항목은 앱 안 이동으로 만들어진 항목이 아님", () => { + stubHistory(null); + + expect(isCurrentHistoryEntryInApp()).toBe(false); + }); + + it("표시한 항목은 앱 안 이동으로 만들어진 항목이며 기존 state를 유지함", () => { + const history = stubHistory({ __NA: true }); + + markCurrentHistoryEntryInApp(); + + expect(isCurrentHistoryEntryInApp()).toBe(true); + expect(history.state).toEqual({ __NA: true, globberInApp: true }); + }); + + it("history를 쓸 수 없으면 표시하지 않고 직접 진입으로 봄", () => { + vi.stubGlobal("window", { + history: { + get state() { + throw new Error("blocked"); + }, + replaceState: () => { + throw new Error("blocked"); + }, + }, + }); + + markCurrentHistoryEntryInApp(); + + expect(isCurrentHistoryEntryInApp()).toBe(false); + }); +}); diff --git a/apps/web/src/utils/navigation.ts b/apps/web/src/utils/navigation.ts index fd7ba51c..82b4190f 100644 --- a/apps/web/src/utils/navigation.ts +++ b/apps/web/src/utils/navigation.ts @@ -30,6 +30,33 @@ export const hasInAppNavigation = (): boolean => { } }; +/** 앱 안 이동으로 만들어진 history 항목에 남기는 history.state 키 */ +const ENTRY_IN_APP_KEY = "globberInApp"; + +/** + * 현재 history 항목이 앱 안 이동으로 만들어졌다고 표시함 + * sessionStorage 기록은 탭 전체의 이력이라 현재 항목이 앱 안에서 생겼는지는 알 수 없으므로, 항목 자체에 표시를 남김 + */ +export const markCurrentHistoryEntryInApp = () => { + try { + window.history.replaceState({ ...window.history.state, [ENTRY_IN_APP_KEY]: true }, ""); + } catch { + // history를 쓸 수 없으면 표시하지 않음 (뒤로가기는 기본 경로로 감) + } +}; + +/** + * 현재 history 항목이 앱 안 이동으로 만들어졌는지 확인함 + * @returns 앱 안 이동으로 만들어진 항목이면 true, 직접 진입한 항목이면 false + */ +export const isCurrentHistoryEntryInApp = (): boolean => { + try { + return window.history.state?.[ENTRY_IN_APP_KEY] === true; + } catch { + return false; + } +}; + /** * 앱 안에서 이동해 온 화면이면 뒤로 가고, 새 탭·링크로 바로 들어온 화면이면 기본 경로로 이동함 (GLB-239) * 새 탭은 빈 페이지 기록이 있어 history.length로는 바로 들어온 경우를 구분할 수 없음