팝업 (Popup)
"팝업(popup)" 컨테이너를 다른 요소에 선언적으로 앵커링(anchoring, 고정)할 수 있게 해 주는 유틸리티 컴포넌트예요. 이름은 ``에서 영감을 받았어요. 내부적으로 Floating UI를 사용해 툴팁, 드롭다운 등을 위한 검증된 가볍고 완전히 선언적인 위치 지정 유틸리티를 제공해요.
Popup은 스타일은 제공하지 않고 위치 지정만 해줘요! 팝업의 선호 위치(placement), 거리(distance), 스키딩(skidding, 오프셋)은 속성으로 설정할 수 있어요. 앵커를 가리키는 화살표도 표시하고 마음대로 커스터마이징할 수 있어요. 추가 위치 지정 옵션도 아래에 자세히 설명되어 있어요.
_ | SlPopup, Shoelace 2.0부터 제공되고 있으며 stable 상태예요.
출처: 문서
본문
| SlPopup — Since 2.0, stable
Popup은 "팝업" 컨테이너를 다른 요소에 선언적으로 앵커링할 수 있게 해 주는 유틸리티예요.
이 컴포넌트의 이름은 ``에서 영감을 받았어요. 내부적으로 Floating UI를 사용해 툴팁, 드롭다운 등을 위한 검증되었고 가벼우며 완전히 선언적인 위치 지정 유틸리티를 제공해요.
Popup은 스타일을 제공하지 않고 위치 지정만 해 줘요! 팝업의 선호 위치, 거리, 스키딩(오프셋)은 속성으로 설정할 수 있어요. 앵커를 가리키는 화살표를 표시하고 마음대로 커스터마이징할 수 있어요. 추가 위치 지정 옵션들도 아래에서 자세히 설명돼요.
Popup은 요소를 위치시키기 위해 특별히 만들어진 저수준(low-level) 유틸리티예요. 툴팁이나 비슷한 것과 혼동하면 안 돼요. 접근 가능한(accessible) 경험을 제공하지 않기 때문이에요! ``를 올바르게 쓰는 거의 모든 경우는 다른 컴포넌트를 만드는 것과 관련돼 있어요. HTML에서 직접 쓰는 경우는 거의 없을 거예요.
<div class="popup-overview">
<sl-popup placement="top" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<div class="popup-overview-options">
<sl-select label="Placement" name="placement" value="top" class="popup-overview-select">
<sl-option value="top">top</sl-option>
<sl-option value="top-start">top-start</sl-option>
<sl-option value="top-end">top-end</sl-option>
<sl-option value="bottom">bottom</sl-option>
<sl-option value="bottom-start">bottom-start</sl-option>
<sl-option value="bottom-end">bottom-end</sl-option>
<sl-option value="right">right</sl-option>
<sl-option value="right-start">right-start</sl-option>
<sl-option value="right-end">right-end</sl-option>
<sl-option value="left">left</sl-option>
<sl-option value="left-start">left-start</sl-option>
<sl-option value="left-end">left-end</sl-option>
</sl-select>
<sl-input type="number" name="distance" label="distance" value="0"></sl-input>
<sl-input type="number" name="skidding" label="Skidding" value="0"></sl-input>
</div>
<div class="popup-overview-options">
<sl-switch name="active" checked>Active</sl-switch>
<sl-switch name="arrow">Arrow</sl-switch>
</div>
</div>
<script>
const container = document.querySelector('.popup-overview');
const popup = container.querySelector('sl-popup');
const select = container.querySelector('sl-select[name="placement"]');
const distance = container.querySelector('sl-input[name="distance"]');
const skidding = container.querySelector('sl-input[name="skidding"]');
const active = container.querySelector('sl-switch[name="active"]');
const arrow = container.querySelector('sl-switch[name="arrow"]');
select.addEventListener('sl-change', () => (popup.placement = select.value));
distance.addEventListener('sl-input', () => (popup.distance = distance.value));
skidding.addEventListener('sl-input', () => (popup.skidding = skidding.value));
active.addEventListener('sl-change', () => (popup.active = active.checked));
arrow.addEventListener('sl-change', () => (popup.arrow = arrow.checked));
</script>
<style>
.popup-overview sl-popup {
--arrow-color: var(--sl-color-primary-600);
}
.popup-overview span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-overview .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-overview-options {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 1rem;
}
.popup-overview-options sl-select {
width: 160px;
}
.popup-overview-options sl-input {
width: 100px;
}
.popup-overview-options + .popup-overview-options {
margin-top: 1rem;
}
</style>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSelect from '@shoelace-style/shoelace/dist/react/select';
import SlMenuItem from '@shoelace-style/shoelace/dist/react/menu-item';
import SlInput from '@shoelace-style/shoelace/dist/react/input';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-overview sl-popup {
--arrow-color: var(--sl-color-primary-600);
}
.popup-overview span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-overview .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-overview-options {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 1rem;
}
.popup-overview-options sl-select {
width: 160px;
}
.popup-overview-options sl-input {
width: 100px;
}
.popup-overview-options + .popup-overview-options {
margin-top: 1rem;
}
`;
const App = () => {
const [placement, setPlacement] = useState('top');
const [distance, setDistance] = useState(0);
const [skidding, setSkidding] = useState(0);
const [active, setActive] = useState(true);
const [arrow, setArrow] = useState(false);
return (
<>
<div className="popup-overview">
<SlPopup
placement={placement}
active={active || null}
distance={distance}
skidding={skidding}
arrow={arrow || null}
>
<span slot="anchor" />
<div className="box" />
</SlPopup>
<div className="popup-overview-options">
<SlSelect
label="Placement"
name="placement"
value={placement}
className="popup-overview-select"
onSlChange={event => setPlacement(event.target.value)}
>
<SlMenuItem value="top">top</SlMenuItem>
<SlMenuItem value="top-start">top-start</SlMenuItem>
<SlMenuItem value="top-end">top-end</SlMenuItem>
<SlMenuItem value="bottom">bottom</SlMenuItem>
<SlMenuItem value="bottom-start">bottom-start</SlMenuItem>
<SlMenuItem value="bottom-end">bottom-end</SlMenuItem>
<SlMenuItem value="right">right</SlMenuItem>
<SlMenuItem value="right-start">right-start</SlMenuItem>
<SlMenuItem value="right-end">right-end</SlMenuItem>
<SlMenuItem value="left">left</SlMenuItem>
<SlMenuItem value="left-start">left-start</SlMenuItem>
<SlMenuItem value="left-end">left-end</SlMenuItem>
</SlSelect>
<SlInput
type="number"
name="distance"
label="distance"
value={distance}
onSlInput={event => setDistance(event.target.value)}
/>
<SlInput
type="number"
name="skidding"
label="Skidding"
value={skidding}
onSlInput={event => setSkidding(event.target.value)}
/>
</div>
<div className="popup-overview-options">
<SlSwitch checked={active} onSlChange={event => setActive(event.target.checked)}>
Active
</SlSwitch>
<SlSwitch checked={arrow} onSlChange={event => setArrow(event.target.checked)}>
Arrow
</SlSwitch>
</div>
</div>
<style>{css}</style>
</>
);
};
팝업의 앵커는 좌표가 계산 대상이 되지 않으므로 display: contents로 스타일링하면 안 돼요. 하지만 앵커가 `` 요소라면 popup은 할당된 첫 번째 요소를 앵커로 사용해요. 이 동작 덕분에 다른 컴포넌트가 컴포지션을 통해 앵커를 더 쉽게 전달할 수 있어요.
Examples
Activating
팝업은 active 속성이 적용되기 전까지는 비활성 상태로 숨겨져 있어요. 속성을 제거하면 모든 위치 지정 로직과 리스너가 정리되므로, 페이지에 유휴 팝업이 많아도 성능에 영향을 주지 않아요.
<div class="popup-active">
<sl-popup placement="top" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<br />
<sl-switch checked>Active</sl-switch>
</div>
<style>
.popup-active span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-active .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
</style>
<script>
const container = document.querySelector('.popup-active');
const popup = container.querySelector('sl-popup');
const active = container.querySelector('sl-switch');
active.addEventListener('sl-change', () => (popup.active = active.checked));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-active span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-active .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => {
const [active, setActive] = useState(true);
return (
<>
<div className="popup-active">
<SlPopup placement="top" active={active}>
<span slot="anchor" />
<div className="box" />
</SlPopup>
<br />
<SlSwitch checked={active} onSlChange={event => setActive(event.target.checked)}>
Active
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
External Anchors
기본적으로 앵커는 anchor 슬롯을 통해 팝업 안에 슬롯됩니다. 앵커를 팝업 바깥에 둬야 한다면, anchor 속성에 앵커의 id를 넘기면 돼요. 또는 anchor 프로퍼티에 요소 참조를 넘겨 id 없이 같은 효과를 낼 수도 있어요.
<span id="external-anchor"></span>
<sl-popup anchor="external-anchor" placement="top" active>
<div class="box"></div>
</sl-popup>
<style>
#external-anchor {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px 0 0 50px;
}
#external-anchor ~ sl-popup .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
</style>
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
const css = `
#external-anchor {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px 0 0 50px;
}
#external-anchor ~ sl-popup .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => {
return (
<>
<span id="external-anchor" />
<SlPopup anchor="external-anchor" placement="top" active>
<div class="box" />
</SlPopup>
<style>{css}</style>
</>
);
};
Placement
placement 속성으로 팝업의 선호 위치를 알려줄 수 있어요. flip과 shift 같은 위치 지정 기능을 쓸 때는 실제 위치가 패널을 뷰포트 안에 유지하기 위해 달라질 수 있다는 점을 기억하세요.
flip을 쓰면 placement가 선호값이 되므로, 활성 상태일 때 data-current-placement 속성을 보면 팝업의 현재 위치를 관찰할 수 있어요. 이 속성은 팝업이 공간을 찾아 플립되면서 업데이트되고, 팝업이 비활성화되면 제거돼요.
<div class="popup-placement">
<sl-popup placement="top" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<sl-select label="Placement" value="top">
<sl-option value="top">top</sl-option>
<sl-option value="top-start">top-start</sl-option>
<sl-option value="top-end">top-end</sl-option>
<sl-option value="bottom">bottom</sl-option>
<sl-option value="bottom-start">bottom-start</sl-option>
<sl-option value="bottom-end">bottom-end</sl-option>
<sl-option value="right">right</sl-option>
<sl-option value="right-start">right-start</sl-option>
<sl-option value="right-end">right-end</sl-option>
<sl-option value="left">left</sl-option>
<sl-option value="left-start">left-start</sl-option>
<sl-option value="left-end">left-end</sl-option>
</sl-select>
</div>
<style>
.popup-placement span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-placement .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-placement sl-select {
max-width: 280px;
}
</style>
<script>
const container = document.querySelector('.popup-placement');
const popup = container.querySelector('sl-popup');
const select = container.querySelector('sl-select');
select.addEventListener('sl-change', () => (popup.placement = select.value));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSelect from '@shoelace-style/shoelace/dist/react/select';
import SlMenuItem from '@shoelace-style/shoelace/dist/react/menu-item';
const css = `
.popup-placement span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-placement .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-placement sl-select {
max-width: 280px;
}
`;
const App = () => {
const [placement, setPlacement] = useState('top');
return (
<div className="popup-active">
<div className="popup-placement">
<SlPopup placement={placement} active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
<SlSelect label="Placement" value={placement} onSlChange={event => setPlacement(event.target.value)}>
<SlMenuItem value="top">top</SlMenuItem>
<SlMenuItem value="top-start">top-start</SlMenuItem>
<SlMenuItem value="top-end">top-end</SlMenuItem>
<SlMenuItem value="bottom">bottom</SlMenuItem>
<SlMenuItem value="bottom-start">bottom-start</SlMenuItem>
<SlMenuItem value="bottom-end">bottom-end</SlMenuItem>
<SlMenuItem value="right">right</SlMenuItem>
<SlMenuItem value="right-start">right-start</SlMenuItem>
<SlMenuItem value="right-end">right-end</SlMenuItem>
<SlMenuItem value="left">left</SlMenuItem>
<SlMenuItem value="left-start">left-start</SlMenuItem>
<SlMenuItem value="left-end">left-end</SlMenuItem>
</SlSelect>
</div>
<style>{css}</style>
</div>
);
};
Distance
distance 속성으로 팝업과 앵커 사이의 거리를 바꿀 수 있어요. 양수 값은 팝업을 더 멀리, 음수 값은 더 가깝게 이동시켜요.
<div class="popup-distance">
<sl-popup placement="top" distance="0" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<sl-range min="-50" max="50" step="1" value="0" label="Distance"></sl-range>
</div>
<style>
.popup-distance span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-distance .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-distance sl-range {
max-width: 260px;
}
</style>
<script>
const container = document.querySelector('.popup-distance');
const popup = container.querySelector('sl-popup');
const distance = container.querySelector('sl-range');
distance.addEventListener('sl-input', () => (popup.distance = distance.value));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlRange from '@shoelace-style/shoelace/dist/react/range';
const css = `
.popup-distance span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-distance .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-distance sl-range {
max-width: 260px;
}
`;
const App = () => {
const [distance, setDistance] = useState(0);
return (
<>
<div className="popup-distance">
<SlPopup placement="top" distance={distance} active>
<span slot="anchor" />
<div class="box" />
</SlPopup>
<SlRange
label="Distance"
min="-50"
max="50"
step="1"
value={distance}
onSlChange={event => setDistance(event.target.value)}
/>
</div>
<style>{css}</style>
</>
);
};
Skidding
skidding 속성은 distance와 비슷하지만, 앵커의 축을 따라 팝업을 오프셋할 수 있게 해 줘요. 양수와 음수 값 모두 허용돼요.
<div class="popup-skidding">
<sl-popup placement="top" skidding="0" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<sl-range min="-50" max="50" step="1" value="0" label="Skidding"></sl-range>
</div>
<style>
.popup-skidding span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-skidding .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-skidding sl-range {
max-width: 260px;
}
</style>
<script>
const container = document.querySelector('.popup-skidding');
const popup = container.querySelector('sl-popup');
const skidding = container.querySelector('sl-range');
skidding.addEventListener('sl-input', () => (popup.skidding = skidding.value));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlRange from '@shoelace-style/shoelace/dist/react/range';
const css = `
.popup-skidding span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-skidding .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-skidding sl-range {
max-width: 260px;
}
`;
const App = () => {
const [skidding, setSkidding] = useState(0);
return (
<>
<div className="popup-skidding">
<SlPopup placement="top" skidding={skidding} active>
<span slot="anchor"></span>
<div className="box"></div>
</SlPopup>
<SlRange
label="Skidding"
min="-50"
max="50"
step="1"
value={skidding}
onSlChange={event => setSkidding(event.target.value)}
/>
</div>
<style>{css}</style>
</>
);
};
Arrows
arrow 속성으로 팝업에 화살표를 추가할 수 있어요. 화살표 자리를 만들기 위해 distance를 설정해 두는 게 보통 좋아요. 화살표의 색과 크기를 조절하려면 각각 --arrow-color와 --arrow-size 커스텀 프로퍼티를 쓰면 돼요. arrow 파트를 대상으로 그림자나 테두리 같은 추가 스타일을 적용할 수도 있어요.
기본적으로 화살표는 사용 가능한 공간과 arrow-padding을 고려해 앵커의 중앙에 최대한 가깝게 정렬돼요. arrow-placement 속성을 쓰면 대신 팝업의 시작(start), 끝(end), 중앙(center)에 화살표를 강제로 정렬할 수 있어요.
<div class="popup-arrow">
<sl-popup placement="top" arrow arrow-placement="anchor" distance="8" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<div class="popup-arrow-options">
<sl-select label="Placement" name="placement" value="top" class="popup-overview-select">
<sl-option value="top">top</sl-option>
<sl-option value="top-start">top-start</sl-option>
<sl-option value="top-end">top-end</sl-option>
<sl-option value="bottom">bottom</sl-option>
<sl-option value="bottom-start">bottom-start</sl-option>
<sl-option value="bottom-end">bottom-end</sl-option>
<sl-option value="right">right</sl-option>
<sl-option value="right-start">right-start</sl-option>
<sl-option value="right-end">right-end</sl-option>
<sl-option value="left">left</sl-option>
<sl-option value="left-start">left-start</sl-option>
<sl-option value="left-end">left-end</sl-option>
</sl-select>
<sl-select label="Arrow Placement" name="arrow-placement" value="anchor">
<sl-option value="anchor">anchor</sl-option>
<sl-option value="start">start</sl-option>
<sl-option value="end">end</sl-option>
<sl-option value="center">center</sl-option>
</sl-select>
</div>
<div class="popup-arrow-options">
<sl-switch name="arrow" checked>Arrow</sl-switch>
</div>
<style>
.popup-arrow sl-popup {
--arrow-color: var(--sl-color-primary-600);
}
.popup-arrow span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-arrow .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-arrow-options {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 1rem;
}
.popup-arrow-options sl-select {
width: 160px;
}
.popup-arrow-options + .popup-arrow-options {
margin-top: 1rem;
}
</style>
<script>
const container = document.querySelector('.popup-arrow');
const popup = container.querySelector('sl-popup');
const placement = container.querySelector('[name="placement"]');
const arrowPlacement = container.querySelector('[name="arrow-placement"]');
const arrow = container.querySelector('[name="arrow"]');
placement.addEventListener('sl-change', () => (popup.placement = placement.value));
arrowPlacement.addEventListener('sl-change', () => (popup.arrowPlacement = arrowPlacement.value));
arrow.addEventListener('sl-change', () => (popup.arrow = arrow.checked));
</script>
</div>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSelect from '@shoelace-style/shoelace/dist/react/select';
import SlMenuItem from '@shoelace-style/shoelace/dist/react/menu-item';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-arrow sl-popup {
--arrow-color: var(--sl-color-primary-600);
}
.popup-arrow span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-arrow .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-arrow-options {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 1rem;
}
.popup-arrow-options sl-select {
width: 160px;
}
.popup-arrow-options + .popup-arrow-options {
margin-top: 1rem;
}
`;
const App = () => {
const [placement, setPlacement] = useState('top');
const [arrowPlacement, setArrowPlacement] = useState('anchor');
const [arrow, setArrow] = useState(true);
return (
<>
<div className="popup-arrow">
<SlPopup placement={placement} arrow={arrow || null} arrow-placement={arrowPlacement} distance="8" active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
<div className="popup-arrow-options">
<SlSelect
label="Placement"
name="placement"
value={placement}
className="popup-overview-select"
onSlChange={event => setPlacement(event.target.value)}
>
<SlMenuItem value="top">top</SlMenuItem>
<SlMenuItem value="top-start">top-start</SlMenuItem>
<SlMenuItem value="top-end">top-end</SlMenuItem>
<SlMenuItem value="bottom">bottom</SlMenuItem>
<SlMenuItem value="bottom-start">bottom-start</SlMenuItem>
<SlMenuItem value="bottom-end">bottom-end</SlMenuItem>
<SlMenuItem value="right">right</SlMenuItem>
<SlMenuItem value="right-start">right-start</SlMenuItem>
<SlMenuItem value="right-end">right-end</SlMenuItem>
<SlMenuItem value="left">left</SlMenuItem>
<SlMenuItem value="left-start">left-start</SlMenuItem>
<SlMenuItem value="left-end">left-end</SlMenuItem>
</SlSelect>
<SlSelect
label="Arrow Placement"
name="arrow-placement"
value={arrowPlacement}
onSlChange={event => setArrowPlacement(event.target.value)}
>
<SlMenuItem value="anchor">anchor</SlMenuItem>
<SlMenuItem value="start">start</SlMenuItem>
<SlMenuItem value="end">end</SlMenuItem>
<SlMenuItem value="center">center</SlMenuItem>
</SlSelect>
</div>
<div className="popup-arrow-options">
<SlSwitch name="arrow" checked={arrow} onSlChange={event => setArrow(event.target.checked)}>
Arrow
</SlSwitch>
</div>
</div>
<style>{css}</style>
</>
);
};
Syncing with the Anchor's Dimensions
sync 속성을 쓰면 팝업을 앵커 요소와 같은 너비 또는 높이로 만들 수 있어요. 팝업이 트리거와 같은 너비나 높이를 유지해야 하는 컨트롤에 유용해요.
<div class="popup-sync">
<sl-popup placement="top" sync="width" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<sl-select value="width" label="Sync">
<sl-option value="width">Width</sl-option>
<sl-option value="height">Height</sl-option>
<sl-option value="both">Both</sl-option>
<sl-option value="">None</sl-option>
</sl-select>
</div>
<style>
.popup-sync span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-sync .box {
width: 100%;
height: 100%;
min-width: 50px;
min-height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-sync sl-select {
width: 160px;
}
</style>
<script>
const container = document.querySelector('.popup-sync');
const popup = container.querySelector('sl-popup');
const fixed = container.querySelector('sl-switch');
const sync = container.querySelector('sl-select');
sync.addEventListener('sl-change', () => (popup.sync = sync.value));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSelect from '@shoelace-style/shoelace/dist/react/select';
import SlMenuItem from '@shoelace-style/shoelace/dist/react/menu-item';
const css = `
.popup-sync span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-sync .box {
width: 100%;
height: 100%;
min-width: 50px;
min-height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-sync sl-switch {
margin-top: 1rem;
}
`;
const App = () => {
const [sync, setSync] = useState('width');
return (
<>
<div class="popup-sync">
<SlPopup placement="top" sync={sync} active>
<span slot="anchor" />
<div class="box" />
</SlPopup>
<SlSelect value={sync} label="Sync" onSlChange={event => setSync(event.target.value)}>
<SlMenuItem value="width">Width</SlMenuItem>
<SlMenuItem value="height">Height</SlMenuItem>
<SlMenuItem value="both">Both</SlMenuItem>
<SlMenuItem value="">None</SlMenuItem>
</SlSelect>
</div>
<style>{css}</style>
</>
);
};
Positioning Strategy
기본적으로 팝업은 absolute 위치 지정 전략을 사용해 배치돼요. 하지만 앵커가 fixed이거나 overflow: auto|hidden인 컨테이너 안에 있으면 팝업이 잘릴 위험이 있어요. 이 문제를 해결하려면 strategy 속성을 fixed로 설정해 fixed 위치 지정 전략을 쓸 수 있어요.
fixed 위치 지정 전략은 앵커가 fixed일 때 흔들림(점프)을 줄이고, 팝업이 클리핑하는 컨테이너를 벗어날 수 있게 해 줘요. 이 전략을 쓸 때 중요한 것은, 콘텐츠가 자신의 containing block(보통 뷰포트)에 상대적으로 배치된다는 점이에요. 단, 조상 요소가 transform, perspective, filter를 쓰는 경우는 예외예요. 자세한 내용은 이 페이지를 참고하세요.
이 예제에서는 팝업이 fixed일 때 overflow 컨테이너를 벗어나는 모습을 볼 수 있어요. fixed 위치 지정 전략은 absolute보다 성능이 낮은 경향이 있으므로 불필요하게 쓰지 않는 게 좋아요.
스위치를 토글하고 컨테이너를 스크롤하면 차이를 확인할 수 있어요.
<div class="popup-strategy">
<div class="overflow">
<sl-popup placement="top" strategy="fixed" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
</div>
<sl-switch checked>Fixed</sl-switch>
</div>
<style>
.popup-strategy .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-strategy span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 150px 50px;
}
.popup-strategy .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-strategy sl-switch {
margin-top: 1rem;
}
</style>
<script>
const container = document.querySelector('.popup-strategy');
const popup = container.querySelector('sl-popup');
const fixed = container.querySelector('sl-switch');
fixed.addEventListener('sl-change', () => (popup.strategy = fixed.checked ? 'fixed' : 'absolute'));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-strategy .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-strategy span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 150px 50px;
}
.popup-strategy .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-strategy sl-switch {
margin-top: 1rem;
}
`;
const App = () => {
const [fixed, setFixed] = useState(true);
return (
<>
<div className="popup-strategy">
<div className="overflow">
<SlPopup placement="top" strategy={fixed ? 'fixed' : 'absolute'} active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
</div>
<SlSwitch checked={fixed} onSlChange={event => setFixed(event.target.checked)}>
Fixed
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
Flip
팝업이 선호 placement에서 공간이 부족하면, 보이도록 자동으로 플립(뒤집기)할 수 있어요. 그러려면 flip 속성을 쓰면 돼요. 기본적으로 팝업은 반대 placement로 플립하지만, flip-fallback-placement와 flip-fallback-strategy로 선호하는 폴백 placement를 설정할 수 있어요. 플립 동작의 경계(boundary)와 패딩을 제어하는 추가 옵션도 있어요.
컨테이너를 스크롤하면 팝업이 잘리지 않게 플립되는 모습을 볼 수 있어요.
<div class="popup-flip">
<div class="overflow">
<sl-popup placement="top" flip active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
</div>
<br />
<sl-switch checked>Flip</sl-switch>
</div>
<style>
.popup-flip .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-flip span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 150px 50px;
}
.popup-flip .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
</style>
<script>
const container = document.querySelector('.popup-flip');
const popup = container.querySelector('sl-popup');
const flip = container.querySelector('sl-switch');
flip.addEventListener('sl-change', () => (popup.flip = flip.checked));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-flip .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-flip span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 150px 50px;
}
.popup-flip .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => {
const [flip, setFlip] = useState(true);
return (
<>
<div className="popup-flip">
<div className="overflow">
<SlPopup placement="top" flip={flip} active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
</div>
<br />
<SlSwitch checked={flip} onSlChange={event => setFlip(event.target.checked)}>
Flip
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
Flip Fallbacks
flip 속성을 쓰는 동안, 선호 placement에 공간이 없을 때 팝업의 위치를 커스터마이징할 수 있어요. flip-fallback-placements와 flip-fallback-strategy를 쓰면 돼요.
선호 placement에 공간이 없으면 flip-fallback-placement에서 처음으로 적합한 placement가 사용돼요. 이 속성의 값은 공백으로 구분된 여러 placement를 포함하는 문자열이어야 해요. 예: "right bottom".
폴백 placement도 모두 실패하면 최종 placement는 flip-fallback-strategy로 결정돼요. 이 값은 initial(기본값, placement의 위치로 되돌아감) 또는 best-fit(사용 가능한 공간에 따라 위치를 선택)이 될 수 있어요.
컨테이너를 스크롤하면 팝업이 잘리지 않도록 폴백 placement를 바꾸는 모습을 볼 수 있어요.
<div class="popup-flip-fallbacks">
<div class="overflow">
<sl-popup placement="top" flip flip-fallback-placements="right bottom" flip-fallback-strategy="initial" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
</div>
</div>
<style>
.popup-flip-fallbacks .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-flip-fallbacks span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 250px 50px;
}
.popup-flip-fallbacks .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
</style>
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
const css = `
.popup-flip-fallbacks .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-flip-fallbacks span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 250px 50px;
}
.popup-flip-fallbacks .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => {
return (
<>
<div className="popup-flip-fallbacks">
<div className="overflow">
<SlPopup placement="top" flip flip-fallback-placements="right bottom" flip-fallback-strategy="initial" active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
</div>
</div>
<style>{css}</style>
</>
);
};
Shift
팝업이 앵커보다 길면 overflow 컨테이너에 잘릴 위험이 있어요. 이 경우 shift 속성을 써서 팝업을 축을 따라 이동시켜 다시 보이게 할 수 있어요. shiftBoundary와 shift-padding으로 shift 동작을 커스터마이징할 수 있어요.
스위치를 토글하면 차이를 볼 수 있어요.
<div class="popup-shift">
<div class="overflow">
<sl-popup placement="top" shift shift-padding="10" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
</div>
<sl-switch checked>Shift</sl-switch>
</div>
<style>
.popup-shift .overflow {
position: relative;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-shift span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 60px 0 0 10px;
}
.popup-shift .box {
width: 300px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
</style>
<script>
const container = document.querySelector('.popup-shift');
const popup = container.querySelector('sl-popup');
const shift = container.querySelector('sl-switch');
shift.addEventListener('sl-change', () => (popup.shift = shift.checked));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-shift .overflow {
position: relative;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-shift span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 60px 0 0 10px;
}
.popup-shift .box {
width: 300px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
`;
const App = () => {
const [shift, setShift] = useState(true);
return (
<>
<div className="popup-shift">
<div className="overflow">
<SlPopup placement="top" shift={shift} shift-padding="10" active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
</div>
<SlSwitch checked={shift} onSlChange={event => setShift(event.target.checked)}>
Shift
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
Auto-size
auto-size 속성을 쓰면 팝업이 잘리지 않도록 필요할 때 자동으로 크기를 조절해 줘요. 가능한 값은 horizontal, vertical, both예요. autoSizeBoundary와 auto-size-padding으로 이 옵션의 동작을 커스터마이징할 수 있어요. Auto-size는 flip과 잘 어울리지만, auto-size-padding을 쓴다면 flip-padding도 같은 값으로 맞춰 주세요.
auto-size를 쓰면 호스트 요소에 --auto-size-available-width와 --auto-size-available-height 중 하나 또는 둘 다 적용돼요. 이 값들은 클리핑이 발생하기 전에 팝오버가 가질 수 있는 사용 가능한 공간을 결정해요. 이 값들은 캐스케이드되므로, 팝업 콘텐츠의 max-width/height를 설정하고 overflow를 쉽게 제어하는 데 쓸 수 있어요.
컨테이너를 스크롤하면 사용 가능한 공간이 바뀌면서 팝업이 리사이즈되는 모습을 볼 수 있어요.
<div class="popup-auto-size">
<div class="overflow">
<sl-popup placement="top" auto-size="both" auto-size-padding="10" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
</div>
<br />
<sl-switch checked>Auto-size</sl-switch>
</div>
<style>
.popup-auto-size .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-auto-size span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 250px 50px 100px 50px;
}
.popup-auto-size .box {
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
/* This sets the preferred size of the popup's content */
width: 100px;
height: 200px;
/* This sets the maximum dimensions and allows scrolling when auto-size kicks in */
max-width: var(--auto-size-available-width);
max-height: var(--auto-size-available-height);
overflow: auto;
}
</style>
<script>
const container = document.querySelector('.popup-auto-size');
const popup = container.querySelector('sl-popup');
const autoSize = container.querySelector('sl-switch');
autoSize.addEventListener('sl-change', () => (popup.autoSize = autoSize.checked ? 'both' : ''));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-auto-size .overflow {
position: relative;
height: 300px;
border: solid 2px var(--sl-color-neutral-200);
overflow: auto;
}
.popup-auto-size span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 250px 50px 100px 50px;
}
.popup-auto-size .box {
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
/* This sets the preferred size of the popup's content */
width: 100px;
height: 200px;
/* This sets the maximum dimensions and allows scrolling when auto-size kicks in */
max-width: var(--auto-size-available-width);
max-height: var(--auto-size-available-height);
overflow: auto;
}
`;
const App = () => {
const [autoSize, setAutoSize] = useState(true);
return (
<>
<div className="popup-auto-size">
<div className="overflow">
<SlPopup placement="top" auto-size={autoSize ? 'both' || null} auto-size-padding="10" active>
<span slot="anchor" />
<div className="box" />
</SlPopup>
</div>
<br />
<SlSwitch checked={autoSize} onSlChange={event => setAutoSize(event.target.checked)}>
Auto-size
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
Hover Bridge
앵커와 팝업 요소 사이에 간격이 있으면, 이 옵션은 보이지 않는 요소로 그 간격을 채우는 "hover bridge"를 추가해요. 이렇게 하면 포인터가 실제로 요소를 떠나지 않으므로 mouseover와 mouseout 같은 이벤트를 듣는 게 훨씬 자연스러워져요. hover bridge는 팝오버가 활성 상태일 때만 그려져요. 이 예제에서는 설명을 위해 bridge를 주황색으로 표시했어요.
<div class="popup-hover-bridge">
<sl-popup placement="top" hover-bridge distance="10" skidding="0" active>
<span slot="anchor"></span>
<div class="box"></div>
</sl-popup>
<br>
<sl-switch checked>Hover Bridge</sl-switch><br>
<sl-range min="0" max="50" step="1" value="10" label="Distance"></sl-range>
<sl-range min="-50" max="50" step="1" value="0" label="Skidding"></sl-range>
</div>
<style>
.popup-hover-bridge span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-hover-bridge .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-hover-bridge sl-range {
max-width: 260px;
margin-top: .5rem;
}
.popup-hover-bridge sl-popup::part(hover-bridge) {
background: tomato;
opacity: .5;
}
</style>
<script>
const container = document.querySelector('.popup-hover-bridge');
const popup = container.querySelector('sl-popup');
const hoverBridge = container.querySelector('sl-switch');
const distance = container.querySelector('sl-range[label="Distance"]');
const skidding = container.querySelector('sl-range[label="Skidding"]');
distance.addEventListener('sl-input', () => (popup.distance = distance.value));
skidding.addEventListener('sl-input', () => (popup.skidding = skidding.value));
hoverBridge.addEventListener('sl-change', () => (popup.hoverBridge = hoverBridge.checked));
</script>
import { useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlRange from '@shoelace-style/shoelace/dist/react/range';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
.popup-hover-bridge span[slot='anchor'] {
display: inline-block;
width: 150px;
height: 150px;
border: dashed 2px var(--sl-color-neutral-600);
margin: 50px;
}
.popup-hover-bridge .box {
width: 100px;
height: 50px;
background: var(--sl-color-primary-600);
border-radius: var(--sl-border-radius-medium);
}
.popup-hover-bridge sl-range {
max-width: 260px;
margin-top: .5rem;
}
.popup-hover-bridge sl-popup::part(hover-bridge) {
background: tomato;
opacity: .5;
}
`;
const App = () => {
const [hoverBridge, setHoverBridge] = useState(true);
const [distance, setDistance] = useState(10);
const [skidding, setSkidding] = useState(0);
return (
<>
<div class="popup-hover-bridge">
<SlPopup placement="top" hover-bridge={hoverBridge} distance={distance} skidding={skidding} active>
<span slot="anchor" />
<div class="box" />
</SlPopup>
<br />
<SlSwitch
checked={hoverBridge}
onSlChange={event => setHoverBridge(event.target.checked)}
>
Hover Bridge
</SlSwitch><br />
<SlRange
min="0"
max="50"
step="1"
value={distance}
label="Distance"
onSlInput={event => setDistance(event.target.value)}
/>
<SlRange
min="-50"
max="50"
step="1"
value={skidding}
label="Skidding"
onSlInput={event => setSkidding(event.target.value)}
/>
</div>
<style>{css}</style>
</>
);
};
Virtual Elements
대부분의 경우 팝업은 실제 요소에 앵커링돼요. 때로는 요소가 아닌 것에 앵커링하는 게 유용할 수 있어요. 그러려면 VirtualElement를 anchor 프로퍼티에 넘기면 돼요. 가상 요소는 아래처럼 DOMRect 객체를 반환하는 getBoundingClientRect() 함수를 포함해야 해요.
const virtualElement = {
getBoundingClientRect() {
// ...
return { width, height, x, y, top, left, right, bottom };
}
};
이 예제는 가상 요소를 사용해 마우스 커서에 팝업을 고정해요. 그래서 제대로 보려면 마우스가 필요해요.
<div class="popup-virtual-element">
<sl-popup placement="right-start">
<div class="circle"></div>
</sl-popup>
<sl-switch>Highlight mouse cursor</sl-switch>
</div>
<script>
const container = document.querySelector('.popup-virtual-element');
const popup = container.querySelector('sl-popup');
const circle = container.querySelector('.circle');
const enabled = container.querySelector('sl-switch');
let clientX = 0;
let clientY = 0;
// Set the virtual element as a property
popup.anchor = {
getBoundingClientRect() {
return {
width: 0,
height: 0,
x: clientX,
y: clientY,
top: clientY,
left: clientX,
right: clientX,
bottom: clientY
};
}
};
// Only activate the popup when the switch is checked
enabled.addEventListener('sl-change', () => {
popup.active = enabled.checked;
});
// Listen for the mouse to move
document.addEventListener('mousemove', handleMouseMove);
// Update the virtual element as the mouse moves
function handleMouseMove(event) {
clientX = event.clientX;
clientY = event.clientY;
// Reposition the popup when the virtual anchor moves
if (popup.active) {
popup.reposition();
}
}
</script>
<style>
/* If you need to set a z-index, set it on the popup part like this */
.popup-virtual-element sl-popup::part(popup) {
z-index: 1000;
pointer-events: none;
}
.popup-virtual-element .circle {
width: 100px;
height: 100px;
border: solid 4px var(--sl-color-primary-600);
border-radius: 50%;
translate: -50px -50px;
animation: 1s virtual-cursor infinite;
}
@keyframes virtual-cursor {
0% { scale: 1; }
50% { scale: 1.1; }
}
</style>
import { useRef, useState } from 'react';
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
import SlSwitch from '@shoelace-style/shoelace/dist/react/switch';
const css = `
/* If you need to set a z-index, set it on the popup part like this */
.popup-virtual-element sl-popup::part(popup) {
z-index: 1000;
pointer-events: none;
}
.popup-virtual-element .circle {
width: 100px;
height: 100px;
border: solid 4px var(--sl-color-primary-600);
border-radius: 50%;
translate: -50px -50px;
animation: 1s virtual-cursor infinite;
}
@keyframes virtual-cursor {
0% { scale: 1; }
50% { scale: 1.1; }
}
`;
const App = () => {
const [enabled, setEnabled] = useState(false);
const [clientX, setClientX] = useState(0);
const [clientY, setClientY] = useState(0);
const popup = useRef(null);
const circle = useRef(null);
const virtualElement = {
getBoundingClientRect() {
return {
width: 0,
height: 0,
x: clientX,
y: clientY,
top: clientY,
left: clientX,
right: clientX,
bottom: clientY
};
}
};
// Listen for the mouse to move
document.addEventListener('mousemove', handleMouseMove);
// Update the virtual element as the mouse moves
function handleMouseMove(event) {
setClientX(event.clientX);
setClientY(event.clientY);
// Reposition the popup when the virtual anchor moves
if (popup.active) {
popup.current.reposition();
}
}
return (
<>
<div className="popup-virtual-element">
<SlPopup
ref={popup}
placement="right-start"
active={enabled}
anchor={virtualElement}
>
<div ref={circle} className="circle" />
</SlPopup>
<SlSwitch checked={enabled} onSlChange={event => setEnabled(event.target.checked)}>
Highlight mouse cursor
</SlSwitch>
</div>
<style>{css}</style>
</>
);
};
때로는 getBoundingClientRects가 실제 요소에서 파생될 수도 있어요. 이 경우 앵커 요소를 context로 제공해 팝업의 클리핑과 위치 업데이트가 잘 동작하도록 해 주세요.
const virtualElement = {
getBoundingClientRect() {
// ...
return { width, height, x, y, top, left, right, bottom };
},
contextElement: anchorElement
};
Importing
autoloader나 전통적인 loader를 사용하고 있다면 이 부분은 건너뛰어도 돼요. 그 외에는 아래 스니펫 중 원하는 걸 골라 이 컴포넌트만 골라 가져올 수 있어요.
Script / Import / Bundler / React 방식이 준비되어 있어요.
CDN에서 <script> 태그로 이 컴포넌트를 가져오려면:
<script type="module" src="https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/popup/popup.js"></script>
CDN에서 JavaScript import로 가져오려면:
import 'https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.20.1/cdn/components/popup/popup.js';
Bundler를 사용해 가져오려면:
import '@shoelace-style/shoelace/dist/components/popup/popup.js';
React 컴포넌트로 가져오려면:
import SlPopup from '@shoelace-style/shoelace/dist/react/popup';
Slots
| Name | Description |
|---|---|
| (default) | The popup’s content. |
anchor |
The element the popup will be anchored to. If the anchor lives outside of the popup, you can use the |
anchor attribute or property instead. |
슬롯 사용법에 대해 더 알아보세요.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
popup |
A reference to the internal popup container. Useful for animating and styling the popup with | |||
| JavaScript. | HTMLElement |
- | ||
anchor |
The element the popup will be anchored to. If the anchor lives outside of the popup, you can provide |
the anchor element `id`, a DOM element reference, or a `VirtualElement`. If
the anchor lives inside the popup, use the `anchor` slot instead. | | `Element \| string \| VirtualElement` | - |
| active | Activates the positioning logic and shows the popup. When this attribute is removed, the positioning
logic is torn down and the popup will be hidden. | | boolean | false |
| placement | The preferred placement of the popup. Note that the actual placement will vary as configured to keep
the panel inside of the viewport. | | 'top' \| 'top-start' \| 'top-end' \| 'bottom' \| 'bottom-start' \| 'bottom-end' \| 'right' \| 'right-start' \| 'right-end' \| 'left' \| 'left-start' \| 'left-end' 'top' |
| strategy | Determines how the popup is positioned. The absolute strategy works well in most cases,
but if overflow is clipped, using a fixed position strategy can often workaround it. | | 'absolute' \| 'fixed' | 'absolute' |
| distance | The distance in pixels from which to offset the panel away from its anchor. | | number | 0 |
| skidding | The distance in pixels from which to offset the panel along its anchor. | | number | 0 |
| arrow | Attaches an arrow to the popup. The arrow’s size and color can be customized using the
--arrow-size and --arrow-color custom properties. For additional
customizations, you can also target the arrow using ::part(arrow) in your stylesheet. | | boolean | false |
| arrowPlacement
arrow-placement | The placement of the arrow. The default is anchor, which will align the arrow as close
to the center of the anchor as possible, considering available space and arrow-padding.
A value of start, end, or center will align the arrow to the
start, end, or center of the popover instead. | | 'start' \| 'end' \| 'center' \| 'anchor' | 'anchor' |
| arrowPadding
arrow-padding | The amount of padding between the arrow and the edges of the popup. If the popup has a
border-radius, for example, this will prevent it from overflowing the corners. | | number | 10 |
| flip | When set, placement of the popup will flip to the opposite site to keep it in view. You can use
flipFallbackPlacements to further configure how the fallback placement is determined. | | boolean | false |
| flipFallbackPlacements
flip-fallback-placements | If the preferred placement doesn’t fit, popup will be tested in these fallback placements until one
fits. Must be a string of any number of placements separated by a space, e.g. “top bottom left”. If
no placement fits, the flip fallback strategy will be used instead. | | string | '' |
| flipFallbackStrategy
flip-fallback-strategy | When neither the preferred placement nor the fallback placements fit, this value will be used to
determine whether the popup should be positioned using the best available fit based on available
space or as it was initially preferred. | | 'best-fit' \| 'initial' | 'best-fit' |
| flipBoundary | The flip boundary describes clipping element(s) that overflow will be checked relative to when
flipping. By default, the boundary includes overflow ancestors that will cause the element to be
clipped. If needed, you can change the boundary by passing a reference to one or more elements to
this property. | | Element \| Element[] | - |
| flipPadding
flip-padding | The amount of padding, in pixels, to exceed before the flip behavior will occur. | | number | 0 |
| shift | Moves the popup along the axis to keep it in view when clipped. | | boolean | false |
| shiftBoundary | The shift boundary describes clipping element(s) that overflow will be checked relative to when
shifting. By default, the boundary includes overflow ancestors that will cause the element to be
clipped. If needed, you can change the boundary by passing a reference to one or more elements to
this property. | | Element \| Element[] | - |
| shiftPadding
shift-padding | The amount of padding, in pixels, to exceed before the shift behavior will occur. | | number | 0 |
| autoSize
auto-size | When set, this will cause the popup to automatically resize itself to prevent it from overflowing. | | 'horizontal' \| 'vertical' \| 'both' | - |
| sync | Syncs the popup’s width or height to that of the anchor element. | | 'width' \| 'height' \| 'both' | - |
| autoSizeBoundary | The auto-size boundary describes clipping element(s) that overflow will be checked relative to when
resizing. By default, the boundary includes overflow ancestors that will cause the element to be
clipped. If needed, you can change the boundary by passing a reference to one or more elements to
this property. | | Element \| Element[] | - |
| autoSizePadding
auto-size-padding | The amount of padding, in pixels, to exceed before the auto-size behavior will occur. | | number | 0 |
| hoverBridge
hover-bridge | When a gap exists between the anchor and the popup element, this option will add a “hover bridge”
that fills the gap using an invisible element. This makes listening for events such as
mouseenter and mouseleave more sane because the pointer never technically
leaves the element. The hover bridge will only be drawn when the popover is active. | | boolean | false |
| updateComplete | A read-only promise that resolves when the component has
finished updating. | | | |
속성과 프로퍼티에 대해 더 알아보세요.
Events
| Name | React Event | Description | Event Detail |
|---|---|---|---|
sl-reposition |
onSlReposition |
Emitted when the popup is repositioned. This event can fire a lot, so avoid putting expensive | |
| operations in your listener or consider debouncing it. | - |
이벤트에 대해 더 알아보세요.
Methods
| Name | Description | Arguments |
|---|---|---|
reposition() |
Forces the popup to recalculate and reposition itself. | - |
메서드에 대해 더 알아보세요.
Custom Properties
| Name | Description | Default |
|---|---|---|
--arrow-size |
The size of the arrow. Note that an arrow won’t be shown unless the arrow attribute is |
|
| used. | 6px | |
--arrow-color |
The color of the arrow. | var(–sl-color-neutral-0) |
--auto-size-available-width |
A read-only custom property that determines the amount of width the popup can be before overflowing. |
Useful for positioning child elements that need to overflow. This property is only available when
using `auto-size`. | |
| --auto-size-available-height | A read-only custom property that determines the amount of height the popup can be before
overflowing. Useful for positioning child elements that need to overflow. This property is only
available when using auto-size. | |
CSS 커스텀 프로퍼티 커스터마이징에 대해 더 알아보세요.
Parts
| Name | Description |
|---|---|
arrow |
The arrow’s container. Avoid setting top|bottom|left|right properties, as these values |
are assigned dynamically as the popup moves. This is most useful for applying a background color to
match the popup, and maybe a border or box shadow. |
| popup | The popup’s container. Useful for setting a background color, box shadow, etc. |
| hover-bridge | The hover bridge element. Only available when the hover-bridge option is enabled. |
CSS 파트 커스터마이징에 대해 더 알아보세요.
더 알아보기 (Learn more)
- Dropdown 컴포넌트 — popup 위치 지정을 활용하는 컴포넌트
- Tooltip 컴포넌트 — 팝업 기반 툴팁
- Floating UI — popup이 내부적으로 사용하는 위치 지정 라이브러리