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/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/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(); + } + }); +}); diff --git a/apps/web/src/components/imageMetadata/ImageMetadata.tsx b/apps/web/src/components/imageMetadata/ImageMetadata.tsx index 73f1bc8e..e833b5eb 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 { isCurrentHistoryEntryInApp } 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 등)는 현재 history 항목이 앱 안 이동으로 만들어졌는지로 직접 진입 여부를 판단함 const navigation = (window as Window & { navigation?: { canGoBack: boolean } }).navigation; - if (navigation?.canGoBack) { + const canGoBack = navigation ? navigation.canGoBack : isCurrentHistoryEntryInApp(); + if (canGoBack) { router.back(); return; } 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/hooks/useClustering.ts b/apps/web/src/hooks/useClustering.ts index ed877e90..2c9f01b3 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 committedClustersRef = 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,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, @@ -155,6 +159,11 @@ export const useClustering = ({ expandedContinentCountryIds, ]); + // 렌더가 폐기돼도 재사용 기준이 바뀌지 않도록 커밋된 뒤에만 기록함 + useEffect(() => { + committedClustersRef.current = clusteredData; + }, [clusteredData]); + /** * 화면에 표시할 클러스터 아이템 (캐싱) */ 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..c289652b --- /dev/null +++ b/apps/web/src/lib/globe/clustering/reuseClusters.test.ts @@ -0,0 +1,102 @@ +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); +}); + +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 new file mode 100644 index 00000000..82e99984 --- /dev/null +++ b/apps/web/src/lib/globe/clustering/reuseClusters.ts @@ -0,0 +1,64 @@ +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)[]; + +// 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; + + 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 => isSameValue(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; +}; 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; } 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로는 바로 들어온 경우를 구분할 수 없음