본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Context Menu (컨텍스트 메뉴)

원문 보기 위키 갱신

마우스 오른쪽 클릭이나 길게 누르기로 트리거되어 포인터 위치에 표시되는 메뉴 컴포넌트예요. 서브메뉴, 체크 가능한 항목, 라디오 그룹을 지원해요.

출처: 문서

본문

임포트 (Import)

import { ContextMenu } from "@kobalte/core/context-menu";
// or
import { Root, Trigger, ... } from "@kobalte/core/context-menu";
// or (deprecated)
import { ContextMenu } from "@kobalte/core";

기능 (Features)

  • WAI-ARIA Menu and Menubar 디자인 패턴을 따라요.
  • 터치 기기에서는 길게 누르기로 트리거돼요.
  • 모달(modal) 및 비모달(non-modal) 모드를 지원해요.
  • 서브메뉴를 지원해요.
  • 항목, 라벨, 항목 그룹을 지원해요.
  • 선택적 불확정(indeterminate) 상태를 가진 체크 가능한 항목(단일 또는 다중)을 지원해요.
  • 비활성 항목을 지원해요.
  • 접근성을 위한 복잡한 항목 라벨링을 지원해요.
  • 키보드 열기 및 탐색을 지원해요.
  • 키보드 탐색 중 자동 스크롤을 지원해요.
  • 텍스트를 타이핑해 항목에 포커스할 수 있는 타입어헤드(typeahead)를 제공해요.
  • 선택적으로 가리키는 화살표를 렌더링할 수 있어요.
  • 포커스는 완전히 관리돼요.

구조 (Anatomy)

컨텍스트 메뉴는 다음 요소로 구성돼요.

  • ContextMenu: 컨텍스트 메뉴의 루트 컨테이너예요.
  • ContextMenu.Trigger: 메뉴를 토글하는 버튼이에요.
  • ContextMenu.Icon: 메뉴 트리거 안에 표시할 수 있으며 열릴 수 있다는 시각적 단서를 주는 작은 아이콘이에요.
  • ContextMenu.Portal: 메뉴가 열렸을 때 자식들을 body로 포털(portal)해요.
  • ContextMenu.Content: 메뉴가 열렸을 때 렌더링될 콘텐츠를 포함해요.
  • ContextMenu.Arrow: 메뉴 콘텐츠 옆에 렌더링할 선택적 화살표 요소예요.
  • ContextMenu.Separator: 메뉴에서 항목을 시각적으로 구분하는 데 사용돼요.
  • ContextMenu.Group: 여러 항목을 그룹화하는 데 사용돼요. 자동 라벨링을 통한 좋은 접근성을 위해 ContextMenu.GroupLabel과 함께 사용하세요.
  • ContextMenu.GroupLabel: 그룹의 라벨을 렌더링하는 데 사용돼요. 화살표 키로 포커스할 수 없어요.
  • ContextMenu.Sub: 서브메뉴의 모든 부분을 포함해요.
  • ContextMenu.SubTrigger: 서브메뉴를 여는 항목이에요. ContextMenu.Sub 안에 렌더링해야 해요.
  • ContextMenu.SubContent: 서브메뉴가 열렸을 때 튀어나오는 컴포넌트예요. ContextMenu.Sub 안에 렌더링해야 해요.

메뉴 항목은 다음 요소로 구성돼요.

  • ContextMenu.Item: 선택(select)의 항목이에요.
  • ContextMenu.ItemLabel: 항목에 대해 공지될 접근 가능한 라벨이에요.
  • ContextMenu.ItemDescription: 항목에 대해 공지될 선택적 접근 가능한 설명이에요.
  • ContextMenu.ItemIndicator: 항목이 체크됐을 때 렌더링되는 시각적 표시예요.

체크 가능한 메뉴 항목은 다음 요소로 구성돼요.

  • ContextMenu.RadioGroup: 여러 ContextMenu.RadioItem을 그룹화하고 선택을 관리하는 데 사용돼요.
  • ContextMenu.RadioItem: 라디오처럼 제어·렌더링할 수 있는 항목이에요.
  • ContextMenu.CheckboxItem: 체크박스처럼 제어·렌더링할 수 있는 항목이에요.
<ContextMenu>
	<ContextMenu.Trigger>
		<ContextMenu.Icon />
	</ContextMenu.Trigger>

	<ContextMenu.Portal>
		<ContextMenu.Content>
			<ContextMenu.Arrow />

			<ContextMenu.Item>
				<ContextMenu.ItemLabel />
				<ContextMenu.ItemDescription />
			</ContextMenu.Item>

			<ContextMenu.Group>
				<ContextMenu.GroupLabel />
				<ContextMenu.Item />
			</ContextMenu.Group>

			<ContextMenu.CheckboxItem>
				<ContextMenu.ItemIndicator />
			</ContextMenu.CheckboxItem>

			<ContextMenu.RadioGroup>
				<ContextMenu.RadioItem>
					<ContextMenu.ItemIndicator />
				</ContextMenu.RadioItem>
			</ContextMenu.RadioGroup>

			<ContextMenu.Sub>
				<ContextMenu.SubTrigger />
				<ContextMenu.Portal>
					<ContextMenu.SubContent />
				</ContextMenu.Portal>
			</ContextMenu.Sub>

			<ContextMenu.Separator />
		</ContextMenu.Content>
	</ContextMenu.Portal>
</ContextMenu>

예제 (Example)

기본 예제는 공식 문서 페이지에서 확인할 수 있어요.

사용법 (Usage)

원점 인식 애니메이션 (Origin-aware animations)

CSS 사용자 정의 속성 --kb-popper-content-transform-origin을 노출해서 콘텐츠를 계산된 원점에서 애니메이션할 수 있어요.

/* style.css */
.context-menu__content,
.context-menu__sub-content {
	transform-origin: var(--kb-menu-content-transform-origin);
	animation: contentHide 250ms ease-in forwards;
}

.context-menu__content[data-expanded],
.context-menu__sub-content[data-expanded] {
	animation: contentShow 250ms ease-out;
}

@keyframes contentShow {
	from {
		opacity: 0;
		transform: scale(0.96);
	}
	to {
		opacity: 1;
		transform: scale(1);
	}
}

@keyframes contentHide {
	from {
		opacity: 1;
		transform: scale(1);
	}
	to {
		opacity: 0;
		transform: scale(0.96);
	}
}

API 참조 (API Reference)

ContextMenu

ContextMenu는 @kobalte/core/context-menu의 Root 임포트(그리고 더 이상 사용되지 않는 ContextMenu.Root)와 동일해요.

Prop Description
onOpenChange (open: boolean) => void
Event handler called when the open state of the menu changes.
id string
A unique identifier for the component. The id is used to generate id attributes for nested components. If no id prop is provided, a generated id will be used.
modal boolean
Whether the menu should be the only visible content for screen readers, when set to true:
- interaction with outside elements will be disabled.
- scroll will be locked.
- focus will be locked inside the menu content.
- elements outside the menu content will not be visible for screen readers.
preventScroll boolean
Whether the scroll should be locked even if the menu is not modal.
forceMount boolean
Used to force mounting the menu (portal and content) when more control is needed. Useful when controlling animation with SolidJS animation libraries.

ContextMenu는 ContextMenu.Content의 배치를 커스터마이즈하기 위한 다음 prop들도 받아요.

Prop Description
placement Placement
The placement of the menu content.
gutter number
The distance between the menu content and the trigger element. By default, it's 0 plus half of the arrow offset, if it exists.
shift number
The skidding of the menu content along the trigger element.
flip boolean | string
Controls the behavior of the menu content when it overflows the viewport:
- If a boolean, specifies whether the menu content should flip to the opposite side when it overflows.
- If a string, indicates the preferred fallback placements when it overflows.
The placements must be spaced-delimited, e.g. "top left".
slide boolean
Whether the menu content should slide when it overflows.
overlap boolean
Whether the menu content can overlap the trigger element when it overflows.
sameWidth boolean
Whether the menu content should have the same width as the trigger element. This will be exposed to CSS as --kb-popper-anchor-width.
fitViewport boolean
Whether the menu content should fit the viewport. If this is set to true, the menu content will have maxWidth and maxHeight set to the viewport size. This will be exposed to CSS as --kb-popper-available-width and --kb-popper-available-height.
hideWhenDetached boolean
Whether to hide the menu content when the trigger element becomes occluded.
detachedPadding number
The minimum padding in order to consider the trigger element occluded.
arrowPadding number
The minimum padding between the arrow and the menu content corner.
overflowPadding number
The minimum padding between the menu content and the viewport edge. This will be exposed to CSS as --kb-popper-overflow-padding.

ContextMenu.Trigger

Prop Description
disabled boolean
Whether the context menu trigger is disabled or not.
Data attribute Description
data-expanded Present when the menu is open.
data-closed Present when the menu is close.
data-disabled Present when the trigger is disabled.

ContextMenu.Icon, ContextMenu.Content, ContextMenu.SubTrigger 및 ContextMenu.SubContent는 동일한 data-expanded 속성을 공유해요.

ContextMenu.Content

popper positioner는 ContextMenu.Content와 동일한 z-index를 복사해요.

Prop Description
onOpenAutoFocus (event: Event) => void
Event handler called when focus moves into the component after opening. It can be prevented by calling event.preventDefault.
onCloseAutoFocus (event: Event) => void
Event handler called when focus moves to the trigger after closing. It can be prevented by calling event.preventDefault.
onEscapeKeyDown (event: KeyboardEvent) => void
Event handler called when the escape key is down. It can be prevented by calling event.preventDefault.
onPointerDownOutside (event: PointerDownOutsideEvent) => void
Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling event.preventDefault.
onFocusOutside (event: FocusOutsideEvent) => void
Event handler called when the focus moves outside the bounds of the component. It can be prevented by calling event.preventDefault.
onInteractOutside (event: InteractOutsideEvent) => void
Event handler called when an interaction (pointer or focus event) happens outside the bounds of the component. It can be prevented by calling event.preventDefault.

ContextMenu.Arrow

Prop Description
size number
The size of the arrow.

ContextMenu.Item

Prop Description
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the ContextMenu.ItemLabel part if provided, or fallback to the .textContent of the ContextMenu.Item. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is activated.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-highlighted Present when the item is highlighted.

ContextMenu.ItemLabel, ContextMenu.ItemDescription 및 ContextMenu.ItemIndicator는 동일한 data-attributes를 공유해요.

ContextMenu.ItemIndicator

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.

ContextMenu.RadioGroup

Prop Description
value string
The controlled value of the menu radio item to check.
defaultValue string
The value of the menu radio item that should be checked when initially rendered. Useful when you do not need to control the state of the radio group.
onChange (value: string) => void
Event handler called when the value changes.
disabled boolean
Whether the radio group is disabled or not.

ContextMenu.RadioItem

Prop Description
value string
The value of the menu item radio.
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the ContextMenu.ItemLabel part if provided, or fallback to the .textContent of the ContextMenu.Item. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is checked.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-checked Present when the item is checked.
data-highlighted Present when the item is highlighted.

ContextMenu.CheckboxItem

Prop Description
checked boolean
The controlled checked state of the item.
defaultChecked boolean
The default checked state when initially rendered. Useful when you do not need to control the checked state.
onChange (checked: boolean) => void
Event handler called when the checked state of the item changes.
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the ContextMenu.ItemLabel part if provided, or fallback to the .textContent of the ContextMenu.Item. Use this when the content is complex, or you have non-textual content inside.
indeterminate boolean
Whether the item is in an indeterminate state.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is checked/unchecked.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-indeterminate Present when the item is in an indeterminate state.
data-checked Present when the item is checked.
data-highlighted Present when the item is highlighted.

ContextMenu.Sub

Prop Description
open boolean
The controlled open state of the sub menu.
defaultOpen boolean
The default open state when initially rendered. Useful when you do not need to control the open state.
onOpenChange (open: boolean) => void
Event handler called when the open state of the sub menu changes.

ContextMenu.Sub는 ContextMenu.SubContent의 배치를 커스터마이즈하기 위한 다음 prop들도 받아요.

Prop Description
getAnchorRect (anchor?: HTMLElement) => AnchorRect | undefined
Function that returns the trigger element's DOMRect.
gutter number
The distance between the sub menu content and the trigger element. By default, it's 0 plus half of the arrow offset, if it exists.
shift number
The skidding of the sub menu content along the trigger element.
slide boolean
Whether the sub menu content should slide when it overflows.
overlap boolean
Whether the sub menu content can overlap the trigger element when it overflows.
fitViewport boolean
Whether the sub menu content should fit the viewport. If this is set to true, the sub menu content will have maxWidth and maxHeight set to the viewport size. This will be exposed to CSS as --kb-popper-available-width and --kb-popper-available-height.
hideWhenDetached boolean
Whether to hide the sub menu content when the trigger element becomes occluded.
detachedPadding number
The minimum padding in order to consider the trigger element occluded.
arrowPadding number
The minimum padding between the arrow and the sub menu content corner.
overflowPadding number
The minimum padding between the sub menu content and the viewport edge. This will be exposed to CSS as --kb-popper-overflow-padding.

ContextMenu.SubTrigger

Prop Description
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the ContextMenu.SubTrigger. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the sub menu trigger is disabled or not.
Data attribute Description
data-disabled Present when the item is disabled.
data-highlighted Present when the item is highlighted.

ContextMenu.SubContent

Prop Description
onEscapeKeyDown (event: KeyboardEvent) => void
Event handler called when the escape key is down. It can be prevented by calling event.preventDefault.
onPointerDownOutside (event: PointerDownOutsideEvent) => void
Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling event.preventDefault.
onFocusOutside (event: FocusOutsideEvent) => void
Event handler called when the focus moves outside the bounds of the component. It can be prevented by calling event.preventDefault.
onInteractOutside (event: InteractOutsideEvent) => void
Event handler called when an interaction (pointer or focus event) happens outside the bounds of the component. It can be prevented by calling event.preventDefault.

렌더링 요소 (Rendered elements)

Component Default rendered element
ContextMenu none
ContextMenu.Trigger div
ContextMenu.Icon div
ContextMenu.Portal Portal
ContextMenu.Content div
ContextMenu.Arrow div
ContextMenu.Separator hr
ContextMenu.Group div
ContextMenu.GroupLabel span
ContextMenu.Sub none
ContextMenu.SubTrigger div
ContextMenu.SubContent div
ContextMenu.Item div
ContextMenu.ItemLabel div
ContextMenu.ItemDescription div
ContextMenu.ItemIndicator div
ContextMenu.RadioGroup div
ContextMenu.RadioItem div
ContextMenu.CheckboxItem div

접근성 (Accessibility)

키보드 상호작용 (Keyboard Interactions)

Key Description
Space When focus is on an item, activates the item.
Enter When focus is on an item, activates the item.
ArrowDown When focus is on an item, moves focus to the next item.
ArrowUp When focus is on an item, moves focus to the previous item.
ArrowRight / ArrowLeft When focus is on a sub menu trigger, opens or closes the submenu depending on reading direction.
Home When focus is on an item, moves focus to first item.
End When focus is on an item, moves focus to last item.
Esc Closes the context menu.

더 알아보기 (Learn more)