Dialog
Shoelace의 Dialog 컴포넌트(sl-dialog)는 "모달(modal)"이라고도 불리며, 페이지 위에 나타나 사용자의 즉각적인 주의를 요하는 요소예요. 포커스 트래핑(focus trapping), 접근성, 스크롤 제어 등을 지원합니다.
출처: 문서
본문
Dialog는 "모달(modal)"이라고도 불리며, 페이지 위에 나타나 사용자의 즉각적인 주의를 요해요.
<sl-dialog label="Dialog" class="dialog-overview">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-overview');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlDialog label="Dialog" open={open} onSlAfterHide={() => setOpen(false)}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
Examples
Custom Width
--width 커스텀 프로퍼티를 사용해 dialog의 너비를 설정할 수 있어요.
<sl-dialog label="Dialog" class="dialog-width" style="--width: 50vw;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-width');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlDialog label="Dialog" open={open} style={{ '--width': '50vw' }} onSlAfterHide={() => setOpen(false)}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
Scrolling
설계상, dialog의 높이는 결코 뷰포트를 넘지 않아요. 따라서 dialog는 페이지와 함께 스크롤되지 않으므로 헤더와 푸터가 항상 사용자에게 접근 가능함을 보장해요.
<sl-dialog label="Dialog" class="dialog-scrolling">
<div style="height: 150vh; border: dashed 2px var(--sl-color-neutral-200); padding: 0 1rem;">
<p>Scroll down and give it a try! 👇</p>
</div>
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-scrolling');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlDialog label="Dialog" open={open} onSlAfterHide={() => setOpen(false)}>
<div
style={{
height: '150vh',
border: 'dashed 2px var(--sl-color-neutral-200)',
padding: '0 1rem'
}}
>
<p>Scroll down and give it a try! 👇</p>
</div>
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
Header Actions
헤더에는 기본적으로 기능적인 닫기 버튼이 표시돼요. 필요하다면 header-actions 슬롯을 사용해 추가 아이콘 버튼을 넣을 수 있어요.
<sl-dialog label="Dialog" class="dialog-header-actions">
<sl-icon-button class="new-window" slot="header-actions" name="box-arrow-up-right"></sl-icon-button>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-header-actions');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
const newWindowButton = dialog.querySelector('.new-window');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
newWindowButton.addEventListener('click', () => window.open(location.href));
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
import SlIconButton from '@shoelace-style/shoelace/dist/react/icon-button';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlDialog label="Dialog" open={open} onSlAfterHide={() => setOpen(false)}>
<SlIconButton
class="new-window"
slot="header-actions"
name="box-arrow-up-right"
onClick={() => window.open(location.href)}
/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
Preventing the Dialog from Closing
기본적으로 dialog는 사용자가 닫기 버튼을 클릭하거나, 오버레이를 클릭하거나, Escape 키를 누르면 닫혀요. 대부분의 경우 기본 동작이 UX 관점에서 가장 좋아요. 하지만 데이터 손실이 일어나는 경우처럼 그렇게 하면 안 되는 상황도 있어요.
이런 경우 dialog를 열어 두려면 sl-request-close 이벤트를 취소(cancel)하면 돼요. 취소되면 dialog는 계속 열려 있고, 사용자의 주의를 끌기 위해 잠시 펄스(pulse) 효과를 보여줘요.
event.detail.source를 사용해 무엇이 닫기 요청을 트리거했는지 알 수 있어요. 이 예시는 오버레이를 클릭할 때 dialog가 닫히지 않도록 막지만, 닫기 버튼이나 Escape로는 닫히도록 허용해요.
<sl-dialog label="Dialog" class="dialog-deny-close">
This dialog will not close when you click on the overlay.
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-deny-close');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
// Prevent the dialog from closing when the user clicks on the overlay
dialog.addEventListener('sl-request-close', event => {
if (event.detail.source === 'overlay') {
event.preventDefault();
}
});
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
const App = () => {
const [open, setOpen] = useState(false);
// Prevent the dialog from closing when the user clicks on the overlay
function handleRequestClose(event) {
if (event.detail.source === 'overlay') {
event.preventDefault();
}
}
return (
<>
<SlDialog label="Dialog" open={open} onSlRequestClose={handleRequestClose} onSlAfterHide={() => setOpen(false)}>
This dialog will not close when you click on the overlay.
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
Customizing Initial Focus
기본적으로 dialog의 패널은 열릴 때 포커스(focus)를 얻게 돼요. 이렇게 하면 이후에 Tab을 눌렀을 때 dialog 안의 첫 번째 탭 가능(tabbable) 요소에 포커스가 가게 돼요. 다른 요소에 포커스를 두고 싶다면 아래처럼 그 요소에 autofocus 속성(attribute)을 추가하세요.
<sl-dialog label="Dialog" class="dialog-focus">
<sl-input autofocus placeholder="I will have focus when the dialog is opened"></sl-input>
<sl-button slot="footer" variant="primary">Close</sl-button>
</sl-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector('.dialog-focus');
const input = dialog.querySelector('sl-input');
const openButton = dialog.nextElementSibling;
const closeButton = dialog.querySelector('sl-button[slot="footer"]');
openButton.addEventListener('click', () => dialog.show());
closeButton.addEventListener('click', () => dialog.hide());
</script>
import { useState } from 'react';
import SlButton from '@shoelace-style/shoelace/dist/react/button';
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
import SlInput from '@shoelace-style/shoelace/dist/react/input';
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<SlDialog label="Dialog" open={open} onSlAfterHide={() => setOpen(false)}>
<SlInput autofocus placeholder="I will have focus when the dialog is opened" />
<SlButton slot="footer" variant="primary" onClick={() => setOpen(false)}>
Close
</SlButton>
</SlDialog>
<SlButton onClick={() => setOpen(true)}>Open Dialog</SlButton>
</>
);
};
sl-initial-focus 이벤트를 취소하고 이벤트 핸들러 안에서 스스로 포커스를 설정하면 초기 포커스 동작을 더 커스터마이즈할 수 있어요.
Importing
autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 무시해도 돼요. 그 외의 경우 아래 스니펫 중 하나를 골라 이 컴포넌트만 골라(cherry pick) 가져올 수 있답니다.
Script / Import / Bundler / React
CDN에서 script 태그로 이 컴포넌트를 가져오려면:
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/dialog/dialog.js"></script>
CDN에서 JavaScript import로 이 컴포넌트를 가져오려면:
import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/dialog/dialog.js';
bundler를 사용해 이 컴포넌트를 가져오려면:
import '@shoelace-style/shoelace/dist/components/dialog/dialog.js';
이 컴포넌트를 React 컴포넌트로 가져오려면:
import SlDialog from '@shoelace-style/shoelace/dist/react/dialog';
Slots
| Name | Description |
|---|---|
| (default) | The dialog’s main content. |
label |
The dialog’s label. Alternatively, you can use the label attribute. |
header-actions |
Optional actions to add to the header. Works best with sl-icon-button. |
footer |
The dialog’s footer, usually one or more buttons representing various options. |
슬롯(slots) 사용에 대해 더 알아보기.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
modal |
Exposes the internal modal utility that controls focus trapping. To temporarily disable focus trapping and allow third-party modals spawned from an active Shoelace modal, call modal.activateExternal() when the third-party modal opens. Upon closing, call modal.deactivateExternal() to restore Shoelace’s focus trapping. |
- | new Modal(this) |
|
open |
Indicates whether or not the dialog is open. You can toggle this attribute to show and hide the dialog, or you can use the show() and hide() methods and this attribute will reflect the dialog’s open state. |
boolean |
false |
|
label |
The dialog’s label as displayed in the header. You should always include a relevant label even when using no-header, as it is required for proper accessibility. If you need to display HTML, use the label slot instead. |
string |
'' |
|
noHeader / no-header |
Disables the header. This will also remove the default close button, so please ensure you provide an easy, accessible way for users to dismiss the dialog. | boolean |
false |
|
updateComplete |
A read-only promise that resolves when the component has finished updating. |
속성과 프로퍼티(attributes and properties)에 대해 더 알아보기.
Events
| Name | React Event | Description | Event Detail |
|---|---|---|---|
sl-show |
onSlShow |
Emitted when the dialog opens. | - |
sl-after-show |
onSlAfterShow |
Emitted after the dialog opens and all animations are complete. | - |
sl-hide |
onSlHide |
Emitted when the dialog closes. | - |
sl-after-hide |
onSlAfterHide |
Emitted after the dialog closes and all animations are complete. | - |
sl-initial-focus |
onSlInitialFocus |
Emitted when the dialog opens and is ready to receive focus. Calling event.preventDefault() will prevent focusing and allow you to set it on a different element, such as an input. |
- |
sl-request-close |
onSlRequestClose |
Emitted when the user attempts to close the dialog by clicking the close button, clicking the overlay, or pressing escape. Calling event.preventDefault() will keep the dialog open. Avoid using this unless closing the dialog will result in destructive behavior such as data loss. |
{ source: 'close-button' | 'keyboard' | 'overlay' } |
이벤트(events)에 대해 더 알아보기.
Methods
| Name | Description | Arguments |
|---|---|---|
show() |
Shows the dialog. | - |
hide() |
Hides the dialog | - |
메서드(methods)에 대해 더 알아보기.
Custom Properties
| Name | Description | Default |
|---|---|---|
--width |
The preferred width of the dialog. Note that the dialog will shrink to accommodate smaller screens. | |
--header-spacing |
The amount of padding to use for the header. | |
--body-spacing |
The amount of padding to use for the body. | |
--footer-spacing |
The amount of padding to use for the footer. |
CSS 커스텀 프로퍼티(custom properties) 커스터마이징에 대해 더 알아보기.
Parts
| Name | Description |
|---|---|
base |
The component’s base wrapper. |
overlay |
The overlay that covers the screen behind the dialog. |
panel |
The dialog’s panel (where the dialog and its content are rendered). |
header |
The dialog’s header. This element wraps the title and header actions. |
header-actions |
Optional actions to add to the header. Works best with sl-icon-button. |
title |
The dialog’s title. |
close-button |
The close button, an sl-icon-button. |
close-button__base |
The close button’s exported base part. |
body |
The dialog’s body. |
footer |
The dialog’s footer. |
CSS 파트(parts) 커스터마이징에 대해 더 알아보기.
Animations
| Name | Description |
|---|---|
dialog.show |
The animation to use when showing the dialog. |
dialog.hide |
The animation to use when hiding the dialog. |
dialog.denyClose |
The animation to use when a request to close the dialog is denied. |
dialog.overlay.show |
The animation to use when showing the dialog’s overlay. |
dialog.overlay.hide |
The animation to use when hiding the dialog’s overlay. |
애니메이션(animations) 커스터마이징에 대해 더 알아보기.
Dependencies
이 컴포넌트는 다음 의존성들을 자동으로 가져와요.
sl-icon-buttonsl-visually-hidden
더 알아보기 (Learn more)
- Shoelace Button 컴포넌트 — dialog 푸터에 자주 넣는 버튼 문서
- Shoelace 시작하기(getting started) — 컴포넌트 설치와 로딩 방법
- Shoelace Drawer 컴포넌트 — 화면 가장자리에서 슬라이드로 열리는 유사한 컴포넌트