탐색

v2.1.0
오버레이

팝오버

팝오버를 여는 버튼을 기준으로 배치되는 떠 있는 패널입니다.

이 페이지의 내용

팝오버는 자신을 연 버튼에 연결된 떠 있는 패널입니다. 원하는 요소에 popover 속성과 .popover를 추가하고, 버튼에서 popovertarget로 해당 요소를 지정하세요. 브라우저는 팝오버를 최상위 레이어로 옮기고, 바깥을 클릭하거나 Esc 키를 누르면 닫습니다. 탭 이동 순서에서는 팝오버가 버튼 바로 다음에 옵니다. 위치는 CSS 앵커 포지셔닝으로 정하므로 별도의 스크립트가 필요 없습니다.

팝오버

<button type="button" class="btn" popovertarget="share">Share</button><div id="share" popover class="popover">  <div class="flex flex-col gap-sm w(260)">    <p class="m(0) fg-text-strong">Share this project</p>    <div class="input-group input-group-sm">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div></div>
<>  <button type="button" className="btn" popoverTarget="share">Share</button>  <div id="share" popover="" className="popover">    <div className="flex flex-col gap-sm w(260)">      <p className="m(0) fg-text-strong">Share this project</p>      <div className="input-group input-group-sm">        <input className="input-group-field" defaultValue="https://atlas.dev/p/9f2c" readOnly aria-label="Link" />        <button type="button" className="btn">Copy</button>      </div>    </div>  </div></>
<button type="button" class="btn" popovertarget="share">Share</button><div id="share" popover class="popover">  <div class="flex flex-col gap-sm w(260)">    <p class="m(0) fg-text-strong">Share this project</p>    <div class="input-group input-group-sm">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div></div>
<template>  <button type="button" class="btn" popovertarget="share">Share</button>  <div id="share" popover class="popover">    <div class="flex flex-col gap-sm w(260)">      <p class="m(0) fg-text-strong">Share this project</p>      <div class="input-group input-group-sm">        <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">        <button type="button" class="btn">Copy</button>      </div>    </div>  </div></template>

#배치

팝오버는 버튼 아래 6px 지점에 열리며 버튼의 시작 쪽 가장자리에 맞춰 정렬됩니다. Popover API가 두 요소를 연결하므로 앵커 이름을 지정하지 않아도 버튼이 앵커가 됩니다. 팝오버가 뷰포트를 벗어날 위치라면 반대쪽에 열립니다.

클래스배치
popover버튼 아래에서 시작 쪽 가장자리에 맞춰 정렬
popover-end버튼이 행 끝에 있을 때 버튼의 끝 쪽 가장자리에 맞춰 정렬
popover-center버튼을 기준으로 가운데 정렬
popover-top버튼 위에 배치. popover-end 또는 popover-center와 함께 사용

배치

<button type="button" class="btn" popovertarget="place-start">Start</button><button type="button" class="btn" popovertarget="place-center">Center</button><button type="button" class="btn" popovertarget="place-end">End</button><button type="button" class="btn" popovertarget="place-top">Top</button><div id="place-start" popover class="popover">Lined up with the start edge.</div><div id="place-center" popover class="popover popover-center">Centered on the button.</div><div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div><div id="place-top" popover class="popover popover-top popover-center">Above the button.</div>
<>  <button type="button" className="btn" popoverTarget="place-start">Start</button>  <button type="button" className="btn" popoverTarget="place-center">Center</button>  <button type="button" className="btn" popoverTarget="place-end">End</button>  <button type="button" className="btn" popoverTarget="place-top">Top</button>  <div id="place-start" popover="" className="popover">Lined up with the start edge.</div>  <div id="place-center" popover="" className="popover popover-center">Centered on the button.</div>  <div id="place-end" popover="" className="popover popover-end">Lined up with the end edge.</div>  <div id="place-top" popover="" className="popover popover-top popover-center">    Above the button.  </div></>
<button type="button" class="btn" popovertarget="place-start">Start</button><button type="button" class="btn" popovertarget="place-center">Center</button><button type="button" class="btn" popovertarget="place-end">End</button><button type="button" class="btn" popovertarget="place-top">Top</button><div id="place-start" popover class="popover">Lined up with the start edge.</div><div id="place-center" popover class="popover popover-center">Centered on the button.</div><div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div><div id="place-top" popover class="popover popover-top popover-center">Above the button.</div>
<template>  <button type="button" class="btn" popovertarget="place-start">Start</button>  <button type="button" class="btn" popovertarget="place-center">Center</button>  <button type="button" class="btn" popovertarget="place-end">End</button>  <button type="button" class="btn" popovertarget="place-top">Top</button>  <div id="place-start" popover class="popover">Lined up with the start edge.</div>  <div id="place-center" popover class="popover popover-center">Centered on the button.</div>  <div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div>  <div id="place-top" popover class="popover popover-top popover-center">Above the button.</div></template>

앵커 포지셔닝을 지원하지 않는 브라우저에서도 팝오버는 열리고 닫힙니다. 이 경우 브라우저의 기본 팝오버 배치에 따라 뷰포트 중앙에 표시됩니다.

#폼이 있는 팝오버

팝오버 안에 컨트롤을 넣을 수 있습니다. 팝오버가 열려도 포커스는 버튼에 남으며, Tab 키를 누르면 팝오버 안으로 이동합니다. 열릴 때 첫 번째 필드에 포커스를 두려면 해당 필드에 autofocus를 추가하세요.

폼이 있는 팝오버

<button type="button" class="btn" popovertarget="rename">Rename</button><form id="rename" popover class="popover">  <div class="flex flex-col gap-sm w(240)">    <label class="field">Project name <input class="input input-sm" value="atlas" autofocus></label>    <div class="flex justify-end gap-xs">      <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">        Cancel      </button>      <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">        Save      </button>    </div>  </div></form>
<>  <button type="button" className="btn" popoverTarget="rename">Rename</button>  <form id="rename" popover="" className="popover">    <div className="flex flex-col gap-sm w(240)">      <label className="field">        Project name <input className="input input-sm" defaultValue="atlas" autoFocus />      </label>      <div className="flex justify-end gap-xs">        <button type="button" className="btn btn-sm" popoverTarget="rename" popoverTargetAction="hide">          Cancel        </button>        <button type="button" className="btn btn-sm btn-primary" popoverTarget="rename" popoverTargetAction="hide">          Save        </button>      </div>    </div>  </form></>
<button type="button" class="btn" popovertarget="rename">Rename</button><form id="rename" popover class="popover">  <div class="flex flex-col gap-sm w(240)">    <label class="field">Project name <input class="input input-sm" value="atlas" autofocus></label>    <div class="flex justify-end gap-xs">      <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">        Cancel      </button>      <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">        Save      </button>    </div>  </div></form>
<template>  <button type="button" class="btn" popovertarget="rename">Rename</button>  <form id="rename" popover class="popover">    <div class="flex flex-col gap-sm w(240)">      <label class="field">        Project name <input class="input input-sm" value="atlas" autofocus>      </label>      <div class="flex justify-end gap-xs">        <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">          Cancel        </button>        <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">          Save        </button>      </div>    </div>  </form></template>

#호버 시 미리보기

링크나 버튼에 호버하거나 포커스를 두면 이동할 곳을 미리 보여 주는 팝오버를 열 수도 있습니다. 팝오버에 popover="hint"를 추가하고, 팝오버를 여는 요소에서 interestfor로 지정하세요. 힌트 팝오버가 열려도 이미 열려 있는 메뉴나 다른 팝오버는 닫히지 않습니다. 콘텐츠는 미리보기로만 제공하세요. 터치 화면에서는 길게 눌러야 볼 수 있으므로, 여기에서만 확인할 수 있는 정보가 있어서는 안 됩니다.

호버 시 열기

<p class="m(0) text-sm fg-text-body">  Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.</p><div id="ada-card" popover="hint" class="popover">  <div class="flex items-center gap-sm">    <span class="avatar avatar-lg"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="flex flex-col">      <span class="fg-text-strong">Ada Lovelace</span>      <span class="text-xs fg-text-muted">Owner · 412 deployments</span>    </div>  </div></div>
<>  <p className="m(0) text-sm fg-text-body">    Deployed by <a className="link" href="#ada" {...{ interestfor: 'ada-card' }}>Ada Lovelace</a> two hours ago.  </p>  <div id="ada-card" popover="hint" className="popover">    <div className="flex items-center gap-sm">      <span className="avatar avatar-lg">        <img className="avatar-image" src="/demo/portrait-1.svg" alt="" />      </span>      <div className="flex flex-col">        <span className="fg-text-strong">Ada Lovelace</span>        <span className="text-xs fg-text-muted">Owner · 412 deployments</span>      </div>    </div>  </div></>
<p class="m(0) text-sm fg-text-body">  Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.</p><div id="ada-card" popover="hint" class="popover">  <div class="flex items-center gap-sm">    <span class="avatar avatar-lg"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="flex flex-col">      <span class="fg-text-strong">Ada Lovelace</span>      <span class="text-xs fg-text-muted">Owner · 412 deployments</span>    </div>  </div></div>
<template>  <p class="m(0) text-sm fg-text-body">    Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.  </p>  <div id="ada-card" popover="hint" class="popover">    <div class="flex items-center gap-sm">      <span class="avatar avatar-lg">        <img class="avatar-image" src="/demo/portrait-1.svg" alt>      </span>      <div class="flex flex-col">        <span class="fg-text-strong">Ada Lovelace</span>        <span class="text-xs fg-text-muted">Owner · 412 deployments</span>      </div>    </div>  </div></template>
이름 위에 포인터를 올리거나 Tab 키로 포커스를 옮기세요.

Chrome과 Edge는 호버나 포커스로 팝오버를 여는 기능(interest invokers)을 지원합니다. 다른 브라우저에서는 링크가 평소처럼 동작하며 미리보기는 표시되지 않습니다.

#접근성

  • 브라우저가 버튼에 aria-expanded를 부여하므로 직접 설정하지 마세요.
  • 팝오버는 비모달이므로 열려 있어도 페이지를 계속 조작할 수 있습니다. 페이지로 돌아가기 전에 작업을 완료하거나 창을 닫아야 한다면 대화 상자를 사용하세요.
  • 실행할 작업 목록에는 메뉴를, 호버할 때 표시할 레이블에는 툴팁을 사용하세요.

#React, Svelte 및 Vue

popover 컴포넌트는 애플리케이션 상태에 따라 팝오버를 열고 닫으며, 브라우저에서 팝오버가 열리거나 닫히면 이를 알려 줍니다. 팝오버를 여는 요소와 그 안의 콘텐츠는 페이지 마크업에서 직접 작성합니다. mode는 auto, manual, hint 중 하나입니다. hint는 마우스를 올렸을 때 표시되는 미리 보기이며, 트리거에 popovertarget 대신 interestfor가 지정되므로 미리 보기를 표시하는 링크나 버튼에 스프레드 구문으로 전달하세요. npx master-ui add popover로 컴포넌트를 프로젝트에 복사하세요. 컴포넌트의 구성과 사용법은 React, Svelte 및 Vue를 참고하세요.

팝오버를 가리키는 트리거가 하나라면 앱 상태로 열 때도 눌러서 열 때와 같은 앵커를 사용합니다. 직접 작성한 스크립트에서는 popover.showPopover({ source: trigger })에 트리거를 전달하세요. 트리거가 여러 개라면 실제로 팝오버를 연 요소를 전달합니다. source를 사용할 수 없을 때도 정해진 트리거를 기준으로 배치하려면 트리거에 details-trigger, 팝오버에 details-popover를 적용하고 같은 앵커 이름을 사용하세요.

app.css
.details-trigger { anchor-name: --details; }.details-popover { position-anchor: --details; }
ui/popover.tsx
'use client'import { useEffect, useId, useReducer, useRef, type ComponentProps, type ReactNode } from 'react'import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'export interface PopoverProps extends Omit<ComponentProps<'div'>, 'popover' | 'ref'> {  /** Whether the popover is open, when this component is told. Leave it out and the trigger opens it. */  open?: boolean  onOpenChange?: (open: boolean) => void  /**   * The button that opens the popover: spread what it is given on a button of your own. In `hint` mode it   * is the link or the button that shows it on hover and on focus, and is given `interestfor`.   */  trigger?: (attributes: PopoverTriggerAttributes) => ReactNode  /**   * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the   * trigger shows while it is hovered or focused, and does not close another popover that is open.   */  mode?: 'auto' | 'manual' | 'hint'}/** What the trigger is given: `popoverTarget` to open the popover, or `interestfor` to show a hint. */export type PopoverTriggerAttributes = { popoverTarget: string } | { interestfor: string }/** * A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this * component only opens and closes it from `open`, and says when the browser did. */export function Popover({ open, onOpenChange, trigger, mode = 'auto', className, id, children, ...root }: PopoverProps) {  const generated = useId()  const name = id ?? generated  const element = useRef<HTMLDivElement>(null)  const heard = useRef(onOpenChange)  /** What the owner knows: the last state it set or was told. */  const known = useRef(false)  const [tick, again] = useReducer((count: number) => count + 1, 0)  useEffect(() => { heard.current = onOpenChange })  useEffect(() => {    const popover = element.current    if (!popover || open === undefined) return    const shown = popover.matches(':popover-open')    known.current = open    if (open && !shown) showFromPopoverTrigger(popover)    else if (!open && shown) popover.hidePopover()  }, [open, tick])  useEffect(() => {    const popover = element.current    if (!popover) return    const report = () => {      const shown = popover.matches(':popover-open')      if (shown !== known.current) heard.current?.(known.current = shown)      // An `open` this component is told wins: if its owner did not take the change, the popover goes back.      again()    }    popover.addEventListener('toggle', report)    return () => popover.removeEventListener('toggle', report)  }, [])  return (    <>      {trigger?.(mode === 'hint' ? { interestfor: name } : { popoverTarget: name })}      <div id={name} popover={mode} className={className ? `popover ${className}` : 'popover'} ref={element} {...root}>{children}</div>    </>  )}
ui/Popover.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface PopoverProps extends Omit<HTMLAttributes<HTMLDivElement>, 'popover'> {    /** Whether the popover is open. Bind it, or leave it out and the trigger opens it. */    open?: boolean    onOpenChange?: (open: boolean) => void    /**     * The button that opens the popover: spread what it is given on a button of your own. In `hint` mode it     * is the link or the button that shows it on hover and on focus, and is given `interestfor`.     */    trigger?: Snippet<[PopoverTriggerAttributes]>    /**     * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the     * trigger shows while it is hovered or focused, and does not close another popover that is open.     */    mode?: 'auto' | 'manual' | 'hint'  }  /** What the trigger is given: `popovertarget` to open the popover, or `interestfor` to show a hint. */  export type PopoverTriggerAttributes = { popovertarget: string } | { interestfor: string }</script><script lang="ts">  import type { Attachment } from 'svelte/attachments'  import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'  let { open = $bindable(), onOpenChange, trigger, mode = 'auto', class: className, id, children, ...root }: PopoverProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  /** What the owner knows: the last state it set or was told. */  let known = false  const presence: Attachment<HTMLDivElement> = (popover) => {    const report = () => {      const shown = popover.matches(':popover-open')      if (shown === known) return      open = known = shown      onOpenChange?.(known)    }    popover.addEventListener('toggle', report)    $effect(() => {      if (open === undefined) return      const shown = popover.matches(':popover-open')      known = open      if (open && !shown) showFromPopoverTrigger(popover)      else if (!open && shown) popover.hidePopover()    })    return () => popover.removeEventListener('toggle', report)  }</script><!--  @component  A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this  component only opens and closes it from `open`, and says when the browser did.-->{@render trigger?.(mode === 'hint' ? { interestfor: name } : { popovertarget: name })}<div id={name} popover={mode} class={['popover', className]} {@attach presence} {...root}>{@render children?.()}</div>
ui/Popover.vue
<script setup lang="ts">import { computed, nextTick, onMounted, useId, useTemplateRef, watch } from 'vue'import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'defineOptions({ inheritAttrs: false })const { id, mode = 'auto' } = defineProps<{  id?: string  /**   * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the   * trigger shows while it is hovered or focused, and does not close another popover that is open.   */  mode?: 'auto' | 'manual' | 'hint'}>()/** Whether the popover is open: `v-model:open`. Leave it out and the trigger opens it. */const open = defineModel<boolean>('open')defineSlots<{  /**   * The button that opens the popover: bind what it is given on a button of your own. In `hint` mode it is   * the link or the button that shows it on hover and on focus, and is given `interestfor`.   */  trigger?: (attributes: { popovertarget: string } | { interestfor: string }) => unknown  default?: () => unknown}>()/* * A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this * component only opens and closes it from `open`, and says when the browser did. */const generated = useId()const name = computed(() => id ?? generated)const triggerAttributes = computed(() => mode === 'hint' ? { interestfor: name.value } : { popovertarget: name.value })const root = useTemplateRef<HTMLDivElement>('root')/** What the owner knows: the last state it set or was told. */let known = falseconst sync = () => {  const popover = root.value  if (!popover || open.value === undefined) return  const shown = popover.matches(':popover-open')  known = open.value  if (open.value && !shown) showFromPopoverTrigger(popover)  else if (!open.value && shown) popover.hidePopover()}const report = () => {  const popover = root.value  if (!popover) return  const shown = popover.matches(':popover-open')  if (shown !== known) open.value = known = shown  // An `open` this component is told wins: if its owner did not take the change, the popover goes back.  void nextTick(sync)}onMounted(sync)watch(open, sync, { flush: 'post' })</script><template>  <slot name="trigger" v-bind="triggerAttributes" />  <div :id="name" :popover="mode" class="popover" ref="root" v-bind="$attrs" @toggle="report"><slot /></div></template>

#클래스

클래스설명
popover떠 있는 패널은 popover 속성이 있는 요소에 적용하며, 이 속성이 없으면 표시되지 않습니다. 버튼 아래에서 시작 가장자리를 맞춰 --anchored-gap (6px)만큼 띄워 열리고, 뷰포트 가장자리에서는 열리는 방향이 반대로 바뀝니다.
popover-end행 끝에 있는 버튼에 사용할 수 있도록 버튼의 끝 가장자리에 맞춰 정렬합니다.적용할 클래스는 popover입니다
popover-center버튼을 기준으로 가운데에 배치합니다.적용할 클래스는 popover입니다
popover-top버튼 위에서 열립니다. popover-end 또는 popover-center와 함께 사용할 수 있습니다.적용할 클래스는 popover입니다

#사용자 지정 속성

속성기본값설명
--popover-padding1rem표면 내부 패딩
--popover-max-width22rem텍스트가 줄바꿈되기 전까지 표면이 넓어질 수 있는 최대 너비입니다.
--anchored-gap표면과 그 표면을 연 컨트롤 사이 간격. 값을 지정하지 않으면 6px입니다.popover에 설정합니다

#소스

@master/ui/components/popover.css
/* * Popover: a floating sheet opened by a button with popovertarget (or commandfor and command="toggle-popover"). * The popover attribute supplies the top layer, light dismiss and Escape; CSS anchor positioning places the * sheet against its button and flips it at the viewport edge. Geometry: a 12px corner, the same as a menu's, * and 16px of padding. */@layer components.ui {  .popover {    --popover-padding: 1rem;    --popover-max-width: 22rem;    --surface-color: var(--color-surface-floating);    width: max-content;    max-width: min(var(--popover-max-width), calc(100vw - 1rem));    /* A long sheet scrolls inside the viewport, as a menu does, instead of running past its edge. */    max-height: calc(100dvh - 1rem);    padding: var(--popover-padding);    border: 0;    border-radius: calc(var(--radius-control-sm) * var(--corner-scale) + 4px);    corner-shape: var(--corner-shape);    overflow: auto;    background: var(--color-surface-floating);    color: var(--color-text-body);    box-shadow: var(--shadow-floating);    font-size: .875rem;    line-height: 1.5;    transform-origin: top;    @apply --anchored;    @apply --pop;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;    overflow-wrap: anywhere;    overscroll-behavior: contain;    /* Line up with the button's end edge instead of its start. */    &.popover-end {      --anchored-inline: span-inline-start;    }    &.popover-center {      --anchored-inline: span-all;    }    /* Open above the button. */    &.popover-top {      --anchored-block: block-start;      transform-origin: bottom;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }}