diff --git a/.claude/skills/fe-a11y/SKILL.md b/.claude/skills/fe-a11y/SKILL.md index d3b2def6..5d764f24 100644 --- a/.claude/skills/fe-a11y/SKILL.md +++ b/.claude/skills/fe-a11y/SKILL.md @@ -51,7 +51,7 @@ paths: 폼 -- [ ] label·설명·오류가 같은 ID 체계와 `aria-describedby`로 연결된다(M5). required는 기호와 programmatic 상태를 함께 가진다. 제출 실패 시 오류 요약으로 포커스가 간다. — DS 8.3절 +- [ ] label·설명·오류가 같은 ID 체계와 `aria-describedby`로 연결된다(M5). required는 기호와 programmatic 상태를 함께 가진다. 입력 오류로 제출이 실패하면 첫 오류 필드로 포커스가 가고, 오류 요약은 그 필드들로 가는 링크다(`src/presentation/forms/use-app-form.ts` `focusFirstError`). 입력 오류가 아닌 실패는 feedback 자리가 포커스를 받는다. — DS 8.3절 - [ ] IME 조합 중에 검증하거나 제출하지 않는다. — DS 8.1절 시각 diff --git a/.claude/skills/fe-ux/SKILL.md b/.claude/skills/fe-ux/SKILL.md index 3cb18f56..afa7fc08 100644 --- a/.claude/skills/fe-ux/SKILL.md +++ b/.claude/skills/fe-ux/SKILL.md @@ -58,7 +58,7 @@ paths: 폼 -- [ ] label·설명·오류가 연결되고, 제출 실패 시 오류 요약으로 포커스가 가며, 요약 항목은 그 필드로 간다. — `docs/design/2026-07-26-design-system-platform-design.md` 8.3절 +- [ ] label·설명·오류가 연결되고, 입력 오류로 제출이 실패하면 첫 오류 필드로 포커스가 가며, 오류 요약 항목은 그 필드로 간다(`src/presentation/forms/use-app-form.ts` `focusFirstError`). — `docs/design/2026-07-26-design-system-platform-design.md` 8.3절 - [ ] 409를 검증 오류로 위장하지 않는다. 이탈 확인(`useDirtyNavigationGuard`)은 성공 저장 뒤 풀고 이동한다. — `docs/design/2026-07-26-typescript-state-and-data-flow-design.md` 8절, `docs/design/2026-07-26-routing-pages-and-patterns-design.md` 6.4절 - [ ] 자동 완성·IME·붙여넣기·비밀번호 관리자를 막지 않는다. 입력을 loading skeleton으로 덮지 않는다. — data-flow 8절 diff --git a/docs/adr/VD-04-native-form-facade.md b/docs/adr/VD-04-native-form-facade.md index 859500a4..083dcc87 100644 --- a/docs/adr/VD-04-native-form-facade.md +++ b/docs/adr/VD-04-native-form-facade.md @@ -73,3 +73,7 @@ React Hook Form과 Zod resolver를 평가한다. rollback 시 reference page는 이전 직접 form/layout으로 돌아갈 수 있다. application input과 outbound gateway 계약은 유지되며, form facade와 template commit은 독립적으로 되돌릴 수 있다. + +## 보완 + +- 2026-11-12: 결정 5(409 conflict는 validation으로 바꾸지 않는다)는 기능이 선언하지 않은 409에 적용된다. 기능이 `useAppForm`의 `refusalMessages`로 선언한 쓰기 전 거절은 409라도 기능의 문구로 필드나 오류 요약에 보이고, 폼은 다음 저장을 받는다(1103/03-01, 매뉴얼 02 결정표 4절). 그 밖의 409는 그대로 충돌이고, `mutation` 옵션을 준 폼은 그 안내를 입력 오류 요약이 아니라 `FormSaveFeedback`에 보인다(1112/04-02). diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index a49d0e6b..07093512 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -579,6 +579,7 @@ export function useInvoiceListFilters(): InvoiceListSearch { - 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿) - 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 다시 보내도 되는 요청(`KEYED`, `IDEMPOTENT`. 뮤테이션 정책의 `resendSafe`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다). +- 폼으로 저장하면 결과 불명 화면을 직접 잇지 않는다. `useAppForm`에 `mutation`과 저장 뒤 할 일(`onSaved`)을 주고 피드백 자리에 `FormSaveFeedback`을 둔다. 확인·재전송, 결과 불명 동안 새 저장 막기, 페이지를 떠난 뒤 끝난 저장이 아무 데도 옮기지 않는 것을 폼이 맡는다. - 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`-create-page.test.tsx`)처럼 400 본문을 손으로 적는다. ② **기준** diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 56da9ac5..529fbabf 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -185,7 +185,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`). - 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다. - 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다. - - 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다. + - 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다. 필드 이름이 붙은 실패라도 결과 불명(`MAYBE_APPLIED`)이면 필드 오류가 아니라 결과 불명으로 보인다. 같은 키 재전송이 쓰기 전에 거절되면, `mutation`을 준 폼은 그 안내를 입력 오류 요약이 아니라 결과 불명 표면(`FormSaveFeedback`)에 보인다. **503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.** diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index 6fa3962b..69c1b92a 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -96,7 +96,7 @@ const search = (q: string) => | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | | 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | -| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트만(쓰기 slice는 `-create-page.test.tsx`) | +| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect`. 폼으로 저장하면 아래 「폼」 행의 `FormSaveFeedback`이 이 둘을 잇는다 | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트(쓰기 slice는 `-create-page.test.tsx`), `tests/component/form-foundation.test.tsx` | | 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | | 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (생성 뼈대 목록은 첫 페이지와 `meta.page.total`만 읽는다) | 런타임 테스트만 | @@ -108,7 +108,7 @@ const search = (q: string) => |---|---|---|---| | 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 쓰기 slice `DetailPage`·`FormPage` | `page-templates-own-layout-only` | | 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 | -| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) | +| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm`. mutation으로 저장하는 폼은 `mutation` 옵션을 주고 피드백 자리에 `FormSaveFeedback`(`src/presentation/forms/form-components.tsx`)을 둔다. 결과 불명 동안 새 저장 막기, 「변경됨으로 확인」, 같은 키 재전송, 다른 저장이 도는 동안의 표시, 마운트된 동안만 저장 뒤 이동(`onSaved`, `FormSaveFeedback`의 `onConfirmed`)을 폼이 맡는다 | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인), `tests/component/form-foundation.test.tsx` | | 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) | | 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features//-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 | diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index bf1367b5..50d6b944 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -589,26 +589,21 @@ export default function ${pascal}DetailPage() { export function renderCreatePage({ names, routeId, write }: SliceShape): string { const { base, camel, pascal, upper } = names; - return `import { useCallback, useEffect, useRef } from "react"; -import { Link, useNavigate } from "react-router-dom"; + return `import { Link, useNavigate } from "react-router-dom"; -import type { Result } from "../../../contracts/result.ts"; import { - AsyncSurface, Button, DirtyNavigationDialog, ErrorSummary, Form, FormActions, - FormFailureStatus, FormField, FormPage, + FormSaveFeedback, useAppForm, useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; import { useLocale } from "../../../presentation/i18n/index.ts"; -import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; -import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; import { ${upper}_FORM_DEFAULTS, ${camel}FormSchema, @@ -634,63 +629,29 @@ export default function ${pascal}CreatePage() { name: message("${camel}.form.name"), } satisfies Record; const mutation = use${pascal}Create(); - // A save outlives this page when the user leaves while it runs. Ending - // then, it does not take them to its item or the list (1106/08-02). - const mounted = useRef(false); - useEffect(() => { - mounted.current = true; - return () => { - mounted.current = false; - }; - }, []); - const openSaved = useCallback( - (outcome: Result<${pascal}ItemView> | null) => { - if (outcome?.ok && mounted.current) { - void navigate( - ${camel}RouteUrl("${write.detail.routeId}", { - params: { ${write.idParam}: outcome.value.itemId }, - }), - ); - } - return outcome; - }, - [navigate], - ); - const submit = useCallback( - async (command: ${pascal}CreateCommand) => { - const outcome = await mutation.submit(command); - openSaved(outcome); - return outcome; - }, - [mutation, openSaved], - ); + // The form holds the rules of a save through the mutation: no new save + // while one is unknown or another runs, confirm and resend of an unknown + // one, and what the page does after a save only while it is still open + // (useAppForm \`mutation\` and \`onSaved\`, FormSaveFeedback). const form = useAppForm({ schema: ${camel}FormSchema, defaultValues: ${upper}_FORM_DEFAULTS, allowedServerFields: ["name"], mapToCommand: to${pascal}CreateCommand, - submit, + submit: mutation.submit, + mutation, + onSaved: (item) => { + void navigate( + ${camel}RouteUrl("${write.detail.routeId}", { + params: { ${write.idParam}: item.itemId }, + }), + ); + }, }); - const effectUnknown = mutation.state.indicator === "mutation-effect-unknown"; - const blocked = effectUnknown || mutation.state.indicator === "mutation-pending"; - // A save this form did not start holds the coordinator (one left running - // when the user came back, or the check behind "confirm applied"): the save - // is off and the feedback says a save is running (1105/08-04). - const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending; const guard = useDirtyNavigationGuard(form.dirty && !form.pending); return ( -
{ - if (blocked) { - event.preventDefault(); - return; - } - void form.submitForm(event); - }} - > + void form.submitForm(event)}> {message("${camel}.list.title")}} @@ -715,38 +676,21 @@ export default function ${pascal}CreatePage() { type="submit" pending={form.pending} pendingLabel={message("${camel}.form.saving")} - disabled={effectUnknown || otherSaveRunning} + disabled={form.effectUnknown || form.otherSaveRunning} > {message("${camel}.form.save")} } feedback={ - form.failure ? ( - void form.submitForm() : undefined} - /> - ) : effectUnknown ? ( - { - void mutation.reconcileUnknownEffect(resolution).then(() => { - form.settleApplied(); - if (mounted.current) void navigate(${camel}RouteUrl("${routeId}")); - }); - }} - // Drawn only for a request with a key (a KEYED command). - onResendUnknownEffect={() => { - void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect())); - }} - /> - ) : otherSaveRunning && form.result !== "effect-unknown" ? ( - - ) : null + { + void navigate(${camel}RouteUrl("${routeId}")); + }} + /> } guard={} /> diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 943488e8..99296c9c 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -282,6 +282,13 @@ type ApplicationMutationController = Readonly<{ * `state.unknownEffectResendable` carries the same answer to `AsyncSurface`. */ canResendUnknownEffect: boolean; + /** + * 1112/01-01. Whether the oldest request is unknown now, read at the + * call, not from the last render: a form asks it when a resend has ended + * (`useAppForm` `mutation`). `state.indicator` says the same once the + * hook renders again. + */ + holdsUnknownEffect(): boolean; }>; type MutationExecution = @@ -878,6 +885,11 @@ export function useApplicationMutation( return submit(head.input as Input); }, [submit, unknownEffectChannel]); + const holdsUnknownEffect = useCallback( + () => unknownEffectChannel?.admissions[0]?.state === "UNKNOWN", + [unknownEffectChannel], + ); + const unknownEffectHead = unknownEffectChannel?.admissions[0]; const canResendUnknownEffect = unknownEffectChannel !== null && @@ -900,6 +912,7 @@ export function useApplicationMutation( reconcileUnknownEffect, resendUnknownEffect, canResendUnknownEffect, + holdsUnknownEffect, }); } diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index 041d3072..f2773888 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -142,6 +142,12 @@ export type AsyncSurfaceProps = Readonly<{ * terminal error shows its own `failure.requestId`. */ supportReference?: string | undefined; + /** + * 1112/04-02. Words about the unknown save shown with it (a resend the + * server refused before the write: `form.resendLater`), not under the input + * error summary. + */ + notice?: ReactNode; }>; export function AsyncSurface({ @@ -155,6 +161,7 @@ export function AsyncSurface({ onResendUnknownEffect, headingLevel, supportReference, + notice, }: AsyncSurfaceProps) { const { message } = useLocale(); if (state.base === "idle") return idle ?? null; @@ -231,6 +238,7 @@ export function AsyncSurface({ {message("action.resendMutation")} ) : null} + {state.indicator === "mutation-effect-unknown" && notice ?

{notice}

: null} {state.indicator === "mutation-effect-unknown" && supportReference ? (

{message("template.supportReference", { diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts index 4ec1456e..535d724f 100644 --- a/src/presentation/design-system/index.ts +++ b/src/presentation/design-system/index.ts @@ -123,6 +123,7 @@ export { FormActions, FormFailureStatus, FormField, + FormSaveFeedback, useAppForm, useDirtyNavigationGuard, } from "../forms/index.ts"; diff --git a/src/presentation/design-system/primitives/checkbox.tsx b/src/presentation/design-system/primitives/checkbox.tsx index bfce9843..b132724b 100644 --- a/src/presentation/design-system/primitives/checkbox.tsx +++ b/src/presentation/design-system/primitives/checkbox.tsx @@ -42,7 +42,11 @@ export const Checkbox = forwardRef( }} type="checkbox" /> - {label} + + {label} + {/* 1112/05-13. The symbol as Field draws it; the state is on the input. */} + {props.required ? : null} + {description ? (

diff --git a/src/presentation/design-system/primitives/dialog.tsx b/src/presentation/design-system/primitives/dialog.tsx index fcb0ea3b..8e1563d2 100644 --- a/src/presentation/design-system/primitives/dialog.tsx +++ b/src/presentation/design-system/primitives/dialog.tsx @@ -41,6 +41,7 @@ export const Dialog = forwardRef( const dialogRef = useRef(null); const previousFocusRef = useRef(null); const focusRestoreGenerationRef = useRef(0); + const innerEscapeRef = useRef(false); const titleId = useId(); const descriptionId = useId(); useImperativeHandle(forwardedRef, () => dialogRef.current!, []); @@ -103,16 +104,26 @@ export const Dialog = forwardRef( className={`ui-dialog ${className}`.trim()} onCancel={(event) => { event.preventDefault(); + // The Escape that fired this cancel closed an inner layer. + if (innerEscapeRef.current) return; onClose(); }} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }} onKeyDown={(event) => { - if (event.key === "Escape") { - event.preventDefault(); - onClose(); + if (event.key !== "Escape") return; + // 1112/05-11. A Menu, Popover or Tooltip inside handled this Escape + // (it prevented the default): it closes that layer, not the Dialog. + if (event.defaultPrevented) { + innerEscapeRef.current = true; + globalThis.setTimeout(() => { + innerEscapeRef.current = false; + }, 0); + return; } + event.preventDefault(); + onClose(); }} ref={dialogRef} > diff --git a/src/presentation/design-system/primitives/escape-layer.ts b/src/presentation/design-system/primitives/escape-layer.ts new file mode 100644 index 00000000..ada44548 --- /dev/null +++ b/src/presentation/design-system/primitives/escape-layer.ts @@ -0,0 +1,15 @@ +/** + * 1112/05-11. Whether an Escape is for a layer drawn over the page (a + * Popover or a shown Tooltip) whose root is `root`. Not when it was pressed + * inside a dialog that does not hold the layer: that Escape is the dialog's. + * An Escape from the layer, from a dialog around it, or from no element + * (focus on the body, as after a click in WebKit) is the layer's. + */ +export function escapeIsForLayer(event: KeyboardEvent, root: Element | null): boolean { + const target = event.target; + if (root === null || !(target instanceof Element) || root.contains(target)) { + return true; + } + const dialog = target.closest("dialog"); + return dialog === null || dialog.contains(root); +} diff --git a/src/presentation/design-system/primitives/popover.tsx b/src/presentation/design-system/primitives/popover.tsx index 98e1438d..6b9e8490 100644 --- a/src/presentation/design-system/primitives/popover.tsx +++ b/src/presentation/design-system/primitives/popover.tsx @@ -1,6 +1,7 @@ import { useEffect, useId, useRef, useState } from "react"; import { Button } from "./button.tsx"; +import { escapeIsForLayer } from "./escape-layer.ts"; export type PopoverProps = Readonly<{ triggerLabel: string; @@ -12,6 +13,7 @@ export function Popover({ triggerLabel, children }: PopoverProps) { const rootRef = useRef(null); const triggerRef = useRef(null); const contentId = useId(); + const triggerId = useId(); useEffect(() => { if (!open) return; @@ -24,17 +26,25 @@ export function Popover({ triggerLabel, children }: PopoverProps) { triggerRef.current?.focus(); } } + // Capture phase, and the default prevented: the Escape closes this + // layer only, not a Dialog around it (1112/05-11). An Escape pressed in + // a Dialog this popover is not in is the Dialog's. function closeOnEscape(event: KeyboardEvent) { - if (event.key === "Escape") { + if ( + event.key === "Escape" && + !event.defaultPrevented && + escapeIsForLayer(event, rootRef.current) + ) { + event.preventDefault(); setOpen(false); triggerRef.current?.focus(); } } document.addEventListener("pointerdown", closeOutside); - document.addEventListener("keydown", closeOnEscape); + document.addEventListener("keydown", closeOnEscape, true); return () => { document.removeEventListener("pointerdown", closeOutside); - document.removeEventListener("keydown", closeOnEscape); + document.removeEventListener("keydown", closeOnEscape, true); }; }, [open]); @@ -43,6 +53,7 @@ export function Popover({ triggerLabel, children }: PopoverProps) { {open ? ( -