Link Preview 문서
Link Preview는 연결된 콘텐츠의 정보를 요약해 미리 보여 주는 컴포넌트예요. 링크를 실제로 따라가기 전에 그 대상이 무엇인지 미리 확인할 수 있어서, 현재 페이지를 벗어나지 않고도 유용한 맥락을 얻을 수 있어요.
출처: 문서
본문
아래 예시에서는 아바타 위에 마우스를 올리면 해당 프로필의 간단한 미리 보기를 보여 줘요. LinkPreview.Trigger에 링크를 걸고, 그 위에 호버하면 LinkPreview.Content가 나타나요.
<script lang="ts">
import { Avatar, LinkPreview } from "bits-ui";
import CalendarBlank from "phosphor-svelte/lib/CalendarBlank";
import MapPin from "phosphor-svelte/lib/MapPin";
</script>
<LinkPreview.Root>
<LinkPreview.Trigger
href="https://x.com/huntabyte"
target="_blank"
rel="noreferrer noopener"
class="rounded-xs underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-8 focus-visible:outline-black"
>
<Avatar.Root
class="data-[status=loaded]:border-foreground bg-muted text-muted-foreground h-12 w-12 rounded-full border border-transparent text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
</LinkPreview.Trigger>
<LinkPreview.Content
class="border-muted bg-background shadow-popover w-[331px] rounded-xl border p-[17px]"
sideOffset={8}
>
<div class="flex space-x-4">
<Avatar.Root
class="data-[status=loaded]:border-foreground bg-muted text-muted-foreground h-12 w-12 rounded-full border border-transparent text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
<div class="space-y-1 text-sm">
<h4 class="font-medium">@huntabyte</h4>
<p>I do things on the internet.</p>
<div
class="text-muted-foreground flex items-center gap-[21px] pt-2 text-xs"
>
<div class="flex items-center text-xs">
<MapPin class="mr-1 size-4" />
<span> FL, USA </span>
</div>
<div class="flex items-center text-xs">
<CalendarBlank class="mr-1 size-4" />
<span> Joined May 2020</span>
</div>
</div>
</div>
</div>
</LinkPreview.Content>
</LinkPreview.Root>
개요 (Overview)
이 컴포넌트는 사용자가 링크를 따라가기로 결정하기 전에 미리 볼 수 있게 해 줘요. 현재 페이지를 벗어나지 않으면서 링크에 대한 필수적이지 않은 맥락이나 추가 정보를 제공하고 싶을 때 유용해요.
모바일 기기에 관한 참고 사항!
이 컴포넌트는 마우스나 그 외 포인팅 장치에서만 사용하도록 만들어졌어요. 터치 이벤트에는 반응하지 않고, 키보드로도 미리 보기 콘텐츠에 접근할 수 없어요. 터치 기기에서는 링크가 즉시 따라가져요. 모든 사용자가 접근할 수 있는 게 아니므로, 미리 보기에는 중요 정보를 담지 않는 게 좋아요.
구조 (Structure)
기본 구조는 Root 안에 Trigger와 Content를 두는 형태예요.
<script lang="ts">
import { LinkPreview } from "bits-ui";
</script>
<LinkPreview.Root>
<LinkPreview.Trigger />
<LinkPreview.Content />
</LinkPreview.Root>
열림 상태 관리 (Managing Open State)
이번엔 컴포넌트의 open 상태를 관리하는 방법을 알아볼게요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동적인 상태 동기화는 bind:open으로 처리해요.
<script lang="ts">
import { LinkPreview } from "bits-ui";
let isOpen = $state(false);
</script>
<button onclick={() => (isOpen = true)}>Open Link Preview</button>
<LinkPreview.Root bind:open={isOpen}>
<!-- ... -->
</LinkPreview.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 전부 제어하고 싶다면 Function Binding을 사용해요.
<script lang="ts">
import { LinkPreview } from "bits-ui";
let myOpen = $state(false);
function getOpen() {
return myOpen;
}
function setOpen(newOpen: boolean) {
myOpen = newOpen;
}
</script>
<LinkPreview.Root bind:open={getOpen, setOpen}>
<!-- ... -->
</LinkPreview.Root>
Floating UI 제외하기 (Opt-out of Floating UI)
LinkPreview.Content 컴포넌트를 사용하면 Bits UI는 다른 팝오버류 컴포넌트처럼 Floating UI를 이용해 트리거에 상대적으로 콘텐츠를 배치해요.
이 대신 LinkPreview.ContentStatic 컴포넌트를 사용하면 이런 동작을 제외할 수 있어요. 이 컴포넌트는 Floating UI를 사용하지 않고, 콘텐츠 배치를 전적으로 사용자가 직접 맡아요.
<LinkPreview.Root>
<LinkPreview.Trigger />
<LinkPreview.ContentStatic>
<!-- ... -->
</LinkPreview.ContentStatic>
</LinkPreview.Root>
참고하세요!
LinkPreview.Arrow 컴포넌트는 Floating UI와 LinkPreview.Content를 함께 쓰도록 설계되었어요. 그래서 LinkPreview.ContentStatic과 함께 쓰려고 하면 예상치 못한 동작이 생길 수 있어요.
커스텀 앵커 (Custom Anchor)
기본적으로 LinkPreview.Content는 트리거의 위치를 기준으로 배치되도록 LinkPreview.Trigger 컴포넌트에 고정돼요.
콘텐츠를 다른 요소에 고정하고 싶다면 LinkPreview.Content 컴포넌트의 customAnchor prop에 선택자 string이나 HTMLElement를 전달하면 돼요.
<script lang="ts">
import { LinkPreview } from "bits-ui";
let customAnchor = $state<HTMLElement>(null!);
</script>
<div bind:this={customAnchor}></div>
<LinkPreview.Root>
<LinkPreview.Trigger />
<LinkPreview.Content {customAnchor}>
<!-- ... -->
</LinkPreview.Content>
</LinkPreview.Root>
Svelte Transitions
forceMount prop과 child 스니펫을 함께 사용하면 LinkPreview.Content 컴포넌트를 강제로 마운트해서 Svelte Transitions이나 더 많은 제어가 필요한 다른 애니메이션 라이브러리를 쓸 수 있어요.
<script lang="ts">
import { LinkPreview } from "bits-ui";
import { fly } from "svelte/transition";
</script>
<LinkPreview.Content forceMount>
{#snippet child({ wrapperProps, props, open })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:fly>
<!-- ... -->
</div>
</div>
{/if}
{/snippet}
</LinkPreview.Content>
물론 이 문법이 가장 깔끔한 건 아니에요. 그래서 이 방법을 쓸 생각이라면 이 로직을 처리하는 나만의 재사용 가능한 콘텐츠 컴포넌트를 만드는 걸 권장해요. Bits UI 컴포넌트에서 트랜지션을 사용하는 방법에 대한 자세한 내용은 Transitions 문서를 확인하세요.
Expand Code
<script lang="ts">
import { Avatar, LinkPreview } from "bits-ui";
import CalendarBlank from "phosphor-svelte/lib/CalendarBlank";
import MapPin from "phosphor-svelte/lib/MapPin";
import { fly } from "svelte/transition";
let loadingStatusTrigger: Avatar.RootProps["loadingStatus"] =
$state("loading");
let loadingStatusContent: Avatar.RootProps["loadingStatus"] =
$state("loading");
</script>
<LinkPreview.Root>
<LinkPreview.Trigger
href="https://github.com/sveltejs"
target="_blank"
rel="noreferrer noopener"
class="rounded-xs underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-8 focus-visible:outline-black"
>
<Avatar.Root
bind:loadingStatus={loadingStatusTrigger}
class="h-12 w-12 rounded-full border {loadingStatusTrigger === 'loaded'
? 'border-foreground'
: 'border-transparent'} bg-muted text-muted-foreground text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border">HB</Avatar.Fallback>
</div>
</Avatar.Root>
</LinkPreview.Trigger>
<LinkPreview.Content
class="border-muted bg-background shadow-popover w-[331px] rounded-xl border p-[17px]"
sideOffset={8}
forceMount
>
{#snippet child({ open, props, wrapperProps })}
{#if open}
<div {...wrapperProps}>
<div {...props} transition:fly={{ duration: 300 }}>
<div class="flex space-x-4">
<Avatar.Root
bind:loadingStatus={loadingStatusContent}
class="h-12 w-12 rounded-full border {loadingStatusContent ===
'loaded'
? 'border-foreground'
: 'border-transparent'} bg-muted text-muted-foreground text-[17px] font-medium uppercase"
>
<div
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
>
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
<Avatar.Fallback class="border-muted border"
>HB</Avatar.Fallback
>
</div>
</Avatar.Root>
<div class="space-y-1 text-sm">
<h4 class="font-medium">@huntabyte</h4>
<p>I do things on the internet.</p>
<div
class="text-muted-foreground flex items-center gap-[21px] pt-2 text-xs"
>
<div class="flex items-center text-xs">
<MapPin class="mr-1 size-4" />
<span> FL, USA </span>
</div>
<div class="flex items-center text-xs">
<CalendarBlank class="mr-1 size-4" />
<span> Joined May 2020</span>
</div>
</div>
</div>
</div>
</div>
</div>
{/if}
{/snippet}
</LinkPreview.Content>
</LinkPreview.Root>
API Reference
LinkPreview.Root
The root component used to manage the state of the state of the link preview.
| Property | Type | Description | Details |
|---|---|---|---|
open $bindable |
boolean |
The open state of the link preview component.Default: false |
|
onOpenChange |
function - (open: boolean) => void |
A callback function called when the open state changes.Default: —— undefined |
|
onOpenChangeComplete |
function - (open: boolean) => void |
A callback function called after the open state changes and all animations have completed.Default: —— undefined |
|
openDelay |
number |
The amount of time in milliseconds to delay opening the preview when hovering over the trigger.Default: 700 |
|
closeDelay |
number |
The amount of time in milliseconds to delay closing the preview when the mouse leaves the trigger.Default: 300 |
|
disabled |
boolean |
Whether or not the link preview is disabled.Default: false |
|
ignoreNonKeyboardFocus |
boolean |
Whether the link preview should ignore non-keyboard focus.Default: false |
|
children |
Snippet |
The children content to render.Default: —— undefined |
LinkPreview.Trigger
A component which triggers the opening and closing of the link preview on hover or focus.
| Property | Type | Description | Details |
|---|---|---|---|
ref $bindable |
HTMLAnchorElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-state |
enum - 'open' | 'closed' |
Whether the accordion item is open or closed. | |
data-link-preview-trigger |
'' |
Present on the trigger element. |
LinkPreview.Content
The contents of the link preview which are displayed when the preview is open.
| Property | Type | Description | Details |
|---|---|---|---|
side |
enum - 'top' | 'bottom' | 'left' | 'right' |
The preferred side of the anchor to render the floating element against when open. Will be reversed when collisions occur.Default: 'bottom' |
|
sideOffset |
number |
The distance in pixels from the anchor to the floating element.Default: 0 |
|
align |
enum - 'start' | 'center' | 'end' |
The preferred alignment of the anchor to render the floating element against when open. This may change when collisions occur.Default: 'start' |
|
alignOffset |
number |
The distance in pixels from the anchor to the floating element.Default: 0 |
|
arrowPadding |
number |
The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.Default: 0 |
|
avoidCollisions |
boolean |
When true, overrides the side and align options to prevent collisions with the boundary edges.Default: true |
|
collisionBoundary |
union - Element | null |
A boundary element or array of elements to check for collisions against.Default: —— undefined |
|
collisionPadding |
union - number | Partial<Record<Side, number>> |
The amount in pixels of virtual padding around the viewport edges to check for overflow which will cause a collision.Default: 0 |
|
sticky |
enum - 'partial' | 'always' |
The sticky behavior on the align axis. 'partial' will keep the content in the boundary as long as the trigger is at least partially in the boundary whilst 'always' will keep the content in the boundary regardless.Default: 'partial' |
|
hideWhenDetached |
boolean |
When true, hides the content when it is detached from the DOM. This is useful for when you want to hide the content when the user scrolls away.Default: true |
|
updatePositionStrategy |
enum - 'optimized' | 'always' |
The strategy to use when updating the position of the content. When 'optimized' the content will only be repositioned when the trigger is in the viewport. When 'always' the content will be repositioned whenever the position changes.Default: 'optimized' |
|
strategy |
enum - 'fixed' | 'absolute' |
The positioning strategy to use for the floating element. When 'fixed' the element will be positioned relative to the viewport. When 'absolute' the element will be positioned relative to the nearest positioned ancestor.Default: 'fixed' |
|
preventScroll |
boolean |
When true, prevents the body from scrolling when the content is open. This is useful when you want to use the content as a modal.Default: true |
|
customAnchor |
union - string | HTMLElement | Measurable | null |
Use an element other than the trigger to anchor the content to. If provided, the content will be anchored to the provided element instead of the trigger.Default: null |
|
onInteractOutside |
function - (event: PointerEvent) => void |
Callback fired when an outside interaction event occurs, which is a pointerdown event. You can call event.preventDefault() to prevent the default behavior of handling the outside interaction.Default: —— undefined |
|
onFocusOutside |
function - (event: FocusEvent) => void |
Callback fired when focus leaves the dismissible layer. You can call event.preventDefault() to prevent the default behavior on focus leaving the layer.Default: —— undefined |
|
interactOutsideBehavior |
enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' |
The behavior to use when an interaction occurs outside of the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close' |
|
onEscapeKeydown |
function - (event: KeyboardEvent) => void |
Callback fired when an escape keydown event occurs in the floating content. You can call event.preventDefault() to prevent the default behavior of handling the escape keydown event.Default: —— undefined |
|
escapeKeydownBehavior |
enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' |
The behavior to use when an escape keydown event occurs in the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close' |
|
onOpenAutoFocus |
function - (event: Event) => void |
Event handler called when auto-focusing the content as it is opened. Can be prevented.Default: —— undefined |
|
onCloseAutoFocus |
function - (event: Event) => void |
Event handler called when auto-focusing the content as it is closed. Can be prevented.Default: —— undefined |
|
trapFocus |
boolean |
Whether or not to trap the focus within the content when open.Default: true |
|
dir |
enum - 'ltr' | 'rtl' |
The reading direction of the app.Default: 'ltr' |
|
forceMount |
boolean |
Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.Default: false |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-state |
enum - 'open' | 'closed' |
Whether the accordion item is open or closed. | |
data-starting-style |
'' |
Present during the initial open frame. Use this to define the starting styles for CSS transitions. | |
data-ending-style |
'' |
Present while closing before unmount. Use this to define the ending styles for CSS transitions. | |
data-link-preview-content |
'' |
Present on the content element. |
| CSS Variable | Description | Details |
|---|---|---|
--bits-link-preview-content-transform-origin |
The transform origin of the content element. | |
--bits-link-preview-content-available-width |
The available width of the content element. | |
--bits-link-preview-content-available-height |
The available height of the content element. | |
--bits-link-preview-anchor-width |
The width of the anchor element. | |
--bits-link-preview-anchor-height |
The height of the anchor element. |
LinkPreview.ContentStatic
The contents of the link preview which are displayed when the preview is open. (Static/No Floating UI)
| Property | Type | Description | Details |
|---|---|---|---|
onInteractOutside |
function - (event: PointerEvent) => void |
Callback fired when an outside interaction event occurs, which is a pointerdown event. You can call event.preventDefault() to prevent the default behavior of handling the outside interaction.Default: —— undefined |
|
onFocusOutside |
function - (event: FocusEvent) => void |
Callback fired when focus leaves the dismissible layer. You can call event.preventDefault() to prevent the default behavior on focus leaving the layer.Default: —— undefined |
|
interactOutsideBehavior |
enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' |
The behavior to use when an interaction occurs outside of the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close' |
|
onEscapeKeydown |
function - (event: KeyboardEvent) => void |
Callback fired when an escape keydown event occurs in the floating content. You can call event.preventDefault() to prevent the default behavior of handling the escape keydown event.Default: —— undefined |
|
escapeKeydownBehavior |
enum - 'close' | 'ignore' | 'defer-otherwise-close' | 'defer-otherwise-ignore' |
The behavior to use when an escape keydown event occurs in the floating content. 'close' will close the content immediately. 'ignore' will prevent the content from closing. 'defer-otherwise-close' will defer to the parent element if it exists, otherwise it will close the content. 'defer-otherwise-ignore' will defer to the parent element if it exists, otherwise it will ignore the interaction.Default: 'close' |
|
onOpenAutoFocus |
function - (event: Event) => void |
Event handler called when auto-focusing the content as it is opened. Can be prevented.Default: —— undefined |
|
onCloseAutoFocus |
function - (event: Event) => void |
Event handler called when auto-focusing the content as it is closed. Can be prevented.Default: —— undefined |
|
trapFocus |
boolean |
Whether or not to trap the focus within the content when open.Default: true |
|
dir |
enum - 'ltr' | 'rtl' |
The reading direction of the app.Default: 'ltr' |
|
forceMount |
boolean |
Whether or not to forcefully mount the content. This is useful if you want to use Svelte transitions or another animation library for the content.Default: false |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-state |
enum - 'open' | 'closed' |
Whether the accordion item is open or closed. | |
data-starting-style |
'' |
Present during the initial open frame. Use this to define the starting styles for CSS transitions. | |
data-ending-style |
'' |
Present while closing before unmount. Use this to define the ending styles for CSS transitions. | |
data-link-preview-content |
'' |
Present on the content element. |
LinkPreview.Arrow
An optional arrow element which points to the trigger when the preview is open.
| Property | Type | Description | Details |
|---|---|---|---|
width |
number |
The width of the arrow in pixels.Default: 8 |
|
height |
number |
The height of the arrow in pixels.Default: 8 |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-link-preview-arrow |
'' |
Present on the arrow element. |
LinkPreview.Portal
When used, will render the link preview content into the body or custom to element when open
| Property | Type | Description | Details |
|---|---|---|---|
to |
union - Element | string |
Where to render the content when it is open. Defaults to the body.Default: document.body |
|
disabled |
boolean |
Whether the portal is disabled or not. When disabled, the content will be rendered in its original DOM location.Default: false |
|
children |
Snippet |
The children content to render.Default: —— undefined |
더 알아보기 (Learn more)
Link Preview는 팝오버 방식으로 링크 대상의 정보를 미리 보여 주는 컴포넌트예요. 다른 팝오버류 컴포넌트처럼 Floating UI로 위치를 제어하고, 트리거에 호버하거나 포커스하면 열리는 구조를 공유해요. 비슷한 상호작용이 필요하다면 Tooltip이나 Popover 문서도 함께 보면 좋아요.