# Alert Dialog URL: /react/stackflow/alert-dialog Source: https://github.com/daangn/seed-design/blob/dev/docs/content/react/stackflow/alert-dialog.mdx Alert Dialog를 Stackflow와 함께 사용하는 방법을 안내합니다. 사용 가능 버전: @seed-design/stackflow@1.1.5, @seed-design/css@1.1.5 Alert Dialog 컴포넌트에 대해 자세히 알아봅니다. ## Making an Alert Dialog Activity **일반적인 경우 Alert Dialog를 [Activity](https://stackflow.so/docs/get-started/activity)로 만들어 사용하는 것을 권장합니다.** - Activity로 관리되므로, 하위 Activity보다 높고 상위 Activity보다는 낮은 z-index를 갖도록 관리하기 쉽습니다. - 딥링킹이 가능합니다. (URL 접속으로 Alert Dialog를 열 수 있습니다.) - [@stackflow/plugin-basic-ui](https://www.npmjs.com/package/@stackflow/plugin-basic-ui) `Modal`에서의 마이그레이션이 쉽습니다. ```tsx title='ActivityAlertDialogActivity.tsx' import { VStack } from "@seed-design/react"; import { useFlow, type StaticActivityComponentType } from "@stackflow/react/future"; import { AppBar, AppBarBackButton, AppBarLeft, AppBarMain, AppBarIconButton, AppBarRight, } from "seed-design/ui/app-bar"; import { AppScreen, AppScreenContent } from "seed-design/ui/app-screen"; import { ActionButton } from "seed-design/ui/action-button"; import { IconHouseLine } from "@karrotmarket/react-monochrome-icon"; declare module "@stackflow/config" { interface Register { ActivityAlertDialogActivity: {}; } } const ActivityAlertDialogActivity: StaticActivityComponentType< "ActivityAlertDialogActivity" > = () => { const { push } = useFlow(); return ( push("ActivityHome", {})}> push("ActivityAlertDialog", {})} > ActivityAlertDialog를 Push push("ActivityAlertDialogActivity", {})} > 지금 열린 이 Activity를 Push ); }; export default ActivityAlertDialogActivity; ``` ```tsx title='ActivityAlertDialog.tsx' import { useActivity, useFlow, type StaticActivityComponentType } from "@stackflow/react/future"; import { useState } from "react"; import { ActionButton } from "seed-design/ui/action-button"; import { AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogRoot, AlertDialogTitle, } from "seed-design/ui/alert-dialog"; import { ResponsivePair, VStack } from "@seed-design/react"; import { send } from "@stackflow/compat-await-push"; import { useActivityZIndexBase } from "@seed-design/stackflow"; import { Switch } from "seed-design/ui/switch"; declare module "@stackflow/config" { interface Register { ActivityAlertDialog: {}; } } const ActivityAlertDialog: StaticActivityComponentType<"ActivityAlertDialog"> = () => { const activity = useActivity(); const { pop, push } = useFlow(); const [keepMounted, setKeepMounted] = useState(false); const handleClose = (open: boolean) => { if (!open) { pop(); send({ activityId: activity.id, data: { message: "hello", }, }); } }; const open = keepMounted ? activity.transitionState === "enter-active" || activity.transitionState === "enter-done" : activity.isActive; const onOpenChange = keepMounted ? (open: boolean) => !open && activity.isActive && handleClose(open) : handleClose; return ( 제목 다람쥐 헌 쳇바퀴에 타고파 확인 push("ActivityDetail", { title: "AlertDialog에서 Push됨", body: keepMounted ? "AlertDialog가 언마운트되지 않았으므로, 현재 Activity를 pop하는 경우 AlertDialog가 열린 상태로 표시됩니다." : "AlertDialog가 언마운트되었으므로, 현재 Activity를 pop하는 경우 AlertDialog가 다시 enter 트랜지션을 재생하며 마운트됩니다.", }) } > Push ); }; export default ActivityAlertDialog; ``` ### Usage ```tsx import { useActivityZIndexBase } from "@seed-design/stackflow"; import { useActivity, useFlow, type ActivityComponentType } from "@stackflow/react/future"; // ... more imports const ActivityAlertDialog: ActivityComponentType<"ActivityAlertDialog"> = () => { const { pop, push } = useFlow(); return ( {/* [!code highlight] */} !open && pop()}> {/* [!code highlight] */} 제목 설명 텍스트 확인 push("AnotherActivity", {})} > 다른 화면으로 이동 ); }; ``` 1. `open` prop에 `useActivity().isActive`를 전달하여 Activity가 활성화될 때 Alert Dialog가 열리도록 합니다. 2. `onOpenChange`를 통해 Alert Dialog가 닫힐 때 `pop()`을 실행하여 Activity를 종료합니다. 3. `layerIndex={useActivityZIndexBase()}`로 Alert Dialog Activity의 z-index 기준점을 전달합니다. - [`useActivityZIndexBase`에 대해 자세히 알아보기](#about-useactivityzindexbase) #### Keeping Alert Dialog Mounted Alert Dialog Activity 위에 다른 Activity를 push할 때 Alert Dialog가 unmount되는 것을 방지하려면, - `open` 상태를 `isActive` 대신 `transitionState`로 관리하고 - `modal` prop을 `isActive`로 설정하고 - `onOpenChange` 핸들러에서 `!isOpen && isActive`인 경우 `pop()`을 실행하도록 합니다. 이 패턴은 Alert Dialog 액티비티 위에 다른 오버레이 컴포넌트 액티비티를 중첩하여 표시하고 싶은 경우 유용합니다. ```tsx const { isActive, transitionState } = useActivity(); return ( !open && isActive && pop()} > {/* ... */} ); ``` 1. `open`을 `transitionState`로 관리하여 다른 Activity가 위에 push되어도 Alert Dialog가 unmount되지 않도록 합니다. 2. `modal={isActive}`로 Alert Dialog Activity가 비활성 상태일 때 `modal`을 `false`로 설정합니다. 이렇게 하지 않으면, 위에 push된 Activity에서 포커스 및 스크린 리더 접근이 동작하지 않습니다. 3. `onOpenChange` 핸들러에서 `isActive`인 경우에만 `pop()`을 실행하여, 비활성 상태에서의 의도치 않은 Activity 종료를 방지합니다. ## Syncing Alert Dialog State with a Step Alert Dialog를 Activity로 만들 수 없는 경우, Alert Dialog가 표시된 상태를 [Step](https://stackflow.so/docs/get-started/navigating-step)으로 만들 수 있습니다. - 현재 Activity를 유지하면서도, 뒤로 가기 버튼 등으로 Alert Dialog를 닫을 수 있습니다. - `AlertDialogTrigger`를 사용하여 Alert Dialog를 열고 닫을 수 있습니다. **Activity로 만들지 않은 Alert Dialog에서 다른 Activity를 push하기 전, z-index 문제를 방지하기 위해 Alert Dialog를 닫으세요.** Alert Dialog를 닫을 수 없거나, Alert Dialog를 연 Activity로 돌아왔을 때 Alert Dialog가 열린 상태를 유지해야 하는 경우 [Alert Dialog를 Activity로](#making-an-alert-dialog-activity) 만들어 사용하는 것을 권장합니다. Activity 간 유려한 트랜지션을 제공하기 위해 하위 AppScreen 요소 중 일부가 상위 AppScreen 요소보다 위에 위치합니다. 이 제약으로 인해, 열린 상태의 Alert Dialog는 독립적인 Activity로 만들지 않는 경우 하위 Activity와 상위 Activity 사이에 위치시키는 것이 불가능합니다. ```tsx title='ActivityAlertDialogStep.tsx' import { HStack, Portal, VStack } from "@seed-design/react"; import { useActivityZIndexBase } from "@seed-design/stackflow"; import { useActivityParams, useFlow, useStepFlow, type StaticActivityComponentType, } from "@stackflow/react/future"; import { useEffect, useState } from "react"; import { ActionButton } from "seed-design/ui/action-button"; import { AppBar, AppBarMain, AppBarIconButton, AppBarRight } from "seed-design/ui/app-bar"; import { AppScreen, AppScreenContent } from "seed-design/ui/app-screen"; import { IconHouseLine } from "@karrotmarket/react-monochrome-icon"; import { AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogRoot, AlertDialogTitle, AlertDialogTrigger, } from "seed-design/ui/alert-dialog"; declare module "@stackflow/config" { interface Register { ActivityAlertDialogStep: { "alert-dialog"?: "open"; }; } } const ActivityAlertDialogStep: StaticActivityComponentType<"ActivityAlertDialogStep"> = () => { const [open, setOpen] = useState(false); const { push } = useFlow(); const { pushStep, popStep } = useStepFlow("ActivityAlertDialogStep"); const params = useActivityParams<"ActivityAlertDialogStep">(); const isOverlayOpen = params["alert-dialog"] === "open"; useEffect(() => setOpen(isOverlayOpen), [isOverlayOpen]); const onOpenChange = (newOpen: boolean) => { setOpen(newOpen); if (newOpen && !isOverlayOpen) { pushStep((params) => ({ ...params, "alert-dialog": "open" })); return; } if (!newOpen && isOverlayOpen) { popStep(); return; } }; return ( push("ActivityHome", {})}> Alert Dialog 열기 Step Alert Dialog가 Step으로 만들어져 있기 때문에 뒤로 가기로 닫을 수 있습니다. setOpen(false)} variant="neutralWeak"> 닫기 { // 이 Alert Dialog는 Activity로 만들어지지 않았기 때문에, z-index 정리를 위해 // Alert Dialog를 먼저 닫고 다음 Activity를 push해야 합니다. setOpen(false); push("ActivityDetail", { title: "Alert Dialog에서 이동한 화면", body: "Alert Dialog를 닫고 이동했습니다.", }); }} > Push ); }; export default ActivityAlertDialogStep; ``` ### Usage ```tsx import { useActivityZIndexBase } from "@seed-design/stackflow"; import { Portal } from "@seed-design/react"; import { useActivity, useActivityParams, useFlow, useStepFlow, type ActivityComponentType, } from "@stackflow/react/future"; import { useEffect, useState } from "react"; // ... more imports declare module "@stackflow/config" { interface Register { ActivityHome: { "alert-dialog"?: "open"; }; } } const ActivityHome: ActivityComponentType<"ActivityHome"> = () => { const [open, setOpen] = useState(false); const { push } = useFlow(); const { pushStep, popStep } = useStepFlow("ActivityHome"); const params = useActivityParams<"ActivityHome">(); // [!code highlight] const isOverlayOpen = params["alert-dialog"] === "open"; // [!code highlight] useEffect(() => { if (!isOverlayOpen) { setOpen(false); } }, [isOverlayOpen]); // [!code highlight] const onOpenChange = (newOpen: boolean) => { setOpen(newOpen); if (newOpen && !isOverlayOpen) { pushStep((params) => ({ ...params, "alert-dialog": "open" })); return; } if (!newOpen && isOverlayOpen) { popStep(); return; } }; return ( Open {/* [!code highlight] */} {/* [!code highlight] */} 제목 설명 텍스트 setOpen(false)}>취소 { // [!code highlight] setOpen(false); // 다른 Activity로 이동하기 전에는 Alert Dialog를 닫으세요. push("ActivityNext"); }} > 다음 {/* [!code highlight] */} ); }; ``` 1. `Portal`을 사용하여 Alert Dialog가 DOM 상 현재 Activity 밖에 렌더링되도록 합니다. 2. `open` prop를 관리하고, `onOpenChange` 핸들러를 통해 Step 상태와 동기화합니다. 3. 뒤로 가기 버튼 등을 통해 Activity 파라미터가 변경될 때 Alert Dialog의 `open` 상태를 동기화합니다. 4. `layerIndex={useActivityZIndexBase({ activityOffset: 1 })}`로 현재 Activity보다 한 단계 높은 z-index 기준점을 전달합니다. - [`useActivityZIndexBase`에 대해 자세히 알아보기](#about-useactivityzindexbase) ### `useStepOverlay` \#2와 #3을 일반화하여 `useStepOverlay`를 사용하면 편리합니다. `useStepOverlay` 구현 예시는 [코드](https://github.com/daangn/seed-design/blob/dev/examples/stackflow-spa/src/seed-design/stackflow/use-step-overlay.ts)를 참고하세요. ```tsx import { useActivityZIndexBase } from "@seed-design/stackflow"; import { Portal } from "@seed-design/react"; import { useStepOverlay } from "./use-step-overlay"; // ... more imports const MyActivity: ActivityComponentType = () => { // [!code highlight] const { overlayProps, setOpen } = useStepOverlay(); const { popStep } = useStepFlow("MyActivity"); const { push } = useFlow(); return ( {/* [!code highlight] */} Open {/* [!code highlight] */} {/* [!code highlight] */} 제목 설명 텍스트 setOpen(false)}>취소 { // [!code highlight] setOpen(false); // 다른 Activity로 이동하기 전에는 Alert Dialog를 닫으세요. push("ActivityNext"); }} > 다음 {/* [!code highlight] */} ); }; ``` ## About `useActivityZIndexBase` `useActivityZIndexBase`는 각 Activity의 z-index 기준점을 반환하는 훅입니다. - `useActivity().zIndex * 5`를 반환합니다. `useActivity().zIndex`는 현재 Activity가 enter된 Activity 중 몇 번째 Activity인지를 나타내는 값입니다. - AppScreen을 구성하는 요소들(layer, appbar, dim, edge)은 `useActivityZIndexBase()` 값을 바탕으로 계산된 z-index를 갖습니다. ``` ┌─ 2번 AlertDialog Activity │ └─ AlertDialog: 12 (2 × 5 + 2) ├─ 1번 AppScreen Activity │ ├─ appbar: 12 (1 × 5 + 7) │ ├─ edge: 9 (1 × 5 + 4) │ ├─ layer: 7 (1 × 5 + 2) │ └─ dim: 5 (1 × 5 + 0) └─ 0번 AppScreen Activity ├─ appbar: 7 (0 × 5 + 7) ├─ edge: 4 (0 × 5 + 4) ├─ layer: 2 (0 × 5 + 2) └─ dim: 0 (0 × 5 + 0) ``` - `activityOffset` 옵션은 현재 Activity가 아닌 다음 Activity의 z-index 기준점을 사용하고 싶을 때 사용합니다. - 예를 들어, `useActivityZIndexBase({ activityOffset: 1 })`는 다음 Activity의 z-index 기준점을 반환합니다. - 이는 Step 패턴에서 현재 Activity 위에 AlertDialog를 표시할 때 유용합니다. ``` ┌─ 1번 AppScreen Activity에서 activityOffset: 1로 띄운 AlertDialog (예: Step 패턴) │ └─ AlertDialog: 12 ((1 + 1) × 5 + 2) ├─ 1번 AppScreen Activity │ ├─ appbar: 12 (1 × 5 + 7) │ ├─ edge: 9 (1 × 5 + 4) │ ├─ layer: 7 (1 × 5 + 2) │ └─ dim: 5 (1 × 5 + 0) └─ 0번 AppScreen Activity ├─ appbar: 7 (0 × 5 + 7) ├─ edge: 4 (0 × 5 + 4) ├─ layer: 2 (0 × 5 + 2) └─ dim: 0 (0 × 5 + 0) ``` - 두 훅 모두 현재 Activity가 enter된 Activity 중 몇 번째 Activity인지를 바탕으로 z-index 스타일링에 필요한 값을 반환하는 훅입니다. - 두 훅이 반환하는 값은 같으나, [@stackflow/plugin-basic-ui](https://www.npmjs.com/package/@stackflow/plugin-basic-ui)가 아닌, SEED 컴포넌트를 사용하는 경우 SEED가 관리하는 `@seed-design/stackflow` 패키지의 `useActivityZIndexBase` 훅을 사용하는 것을 권장합니다. - `@stackflow/react-ui-core` 패키지의 `useZIndexBase`는 `activityOffset` 옵션을 제공하지 않습니다. - `@seed-design/stackflow@1.1.1`부터 `useActivityZIndexBase` 훅이 제공됩니다. `layerIndex`를 `useActivity().zIndex * 5 + n` 형태로 지정하고 있었다면 `useActivityZIndexBase() + n`으로 변경할 수 있습니다. 변경 과정에서 `+ n`이 필요한지 함께 검토해보세요.