Modal

An unstyled, accessible dialog and alertdialog primitive built on top-layer popovers. Features zero layout shifts with scrollbar width compensation, recursive focus trapping, stackable multi-level modals, and glassy backdrops.

Installation

Install the modal layer package.

pnpm add @sv-layer/modal

Basic Dialog

Click the trigger or press Enter/Space. Tab loops focus, Escape or backdrop click closes.

Gordon Freeman · Research Associate

The first example includes its theme import. Additional examples omit decorative styles where noted; use the package theme or global surface styles.

Styling

Headless architecture: works without CSS, comes with an optional theme.

approachhow it works
theme.css (Plug & Play)
import "@sv-layer/modal/theme.css";
Dark dialog card theme with blurred backdrop, layout wrappers, and scale-in entrance transitions.
CSS VariablesUse class, backdropClass or wrapperClass, and a global selector to override theme background, border, radius and shadow. Modal does not publish anchored-positioning variables.
Custom classPass class, backdropClass, or wrapperClass in config.

Alert Dialog

Simulate a destructive confirmation with role='alertdialog'.

Stacked Modals

Multiple overlays stack cleanly in the Top Layer. Escape unwinds one level at a time.

Independent handles

Each handle owns its dialog; attached and programmatic controls share that instance.

Nested layers

The child menu stays interactive above the modal background.

Options

Configuration options for modal(snippet, options).

OptionTypeDefaultDescription
contentSnippet<[close, data]>—Svelte 5 snippet rendered inside dialog card. Receives close() callback.
dataT | () => T—Data passed as second argument to content and onopen.
role"dialog" | "alertdialog""dialog"WAI-ARIA accessible role for assistive technology.
labelstring—Accessible name applied via aria-label.
titleIdstringauto-generatedCustom ID referenced by aria-labelledby.
descriptionIdstringauto-generatedCustom ID referenced by aria-describedby.
closeOnEscapebooleantrueWhether pressing Escape closes the topmost modal.
closeOnOutsideClickbooleantrueWhether clicking outside the dialog card closes the modal.
preventScrollbooleantrueLocks document body scrolling and compensates for scrollbar width.
restoreFocusbooleantrueRestores keyboard focus to the opening trigger upon close.
autoFocusboolean | string | HTMLElement | () => HTMLElementtrueElement to focus on open: first focusable element, selector, or node.
containerHTMLElement | () => HTMLElement | string | nullnullTarget container element. When provided, bounds the modal surface and backdrop inside this container instead of viewport.
portalbooleantrueWhether to portal into browser Top Layer (false bounds to trigger's parent/container).
classstring—CSS class applied to the dialog content card.
backdropClassstring—CSS class applied to the backdrop element.
wrapperClassstring—CSS class applied to the centering layout wrapper.
idstring—Custom HTML id applied to the dialog element.
onopen(data: T) => void—Callback fired when modal opens, receiving resolved data.
onclose() => void—Callback fired when modal closes.
onopenchange(open: boolean) => void—Callback fired on open state change.

Attachment & Handle API

The object returned by modal() functions as an attachment and a reactive handle.

Property / MethodTypeDefaultDescription
isOpenboolean—Reactive boolean flag ($state). True whenever the modal is open in the active overlay stack.
open(data?)(data?: unknown) => void—Programmatically opens the modal dialog with optional dynamic data payload.
close()() => void—Programmatically closes the modal dialog with exit transitions, scroll unlock, and focus restoration.
toggle(data?)(data?: unknown) => void—Toggles modal open or closed.
titleIdstring—Accessible ID for the dialog heading element (bound to aria-labelledby).
descriptionIdstring—Accessible ID for the dialog description element (bound to aria-describedby).
<script lang="ts">
	import { modal } from "@sv-layer/modal";
	import "@sv-layer/modal/theme.css";

	const dialog = modal(dialogContent, {
		role: "dialog",
		label: "Confirm Action",
	});
</script>

{#snippet dialogContent(close: () => void, data: unknown)}
	<div class="modal-card">
		<h3>Action confirmation</h3>
		<p>Are you sure you want to proceed?</p>
		<button onclick={close}>Cancel</button>
		<button onclick={() => { console.log("Confirmed"); close(); }}>Confirm</button>
	</div>
{/snippet}

<!-- Programmatic control without trigger or with @attach -->
<button onclick={() => dialog.open()}>
	Open Dialog ({dialog.isOpen ? "Active" : "Closed"})
</button>

<button {@attach dialog}>Attached trigger</button>

Snippet Parameters

Parameters received by modal content snippets: snippet(close, data).

ParameterTypeDefaultDescription
close() => void—Callback to close the modal dialog with exit animation and restore trigger focus.
dataT—Resolved data payload passed to the modal.

A global modal makes the background inert and locks body scrolling by default. A contained modal limits interaction to its container and does not claim document-wide aria-modal. Exit cleanup waits for the theme animation, with a 600 ms limit; reduced motion skips this wait.

How it works

Top-layer popovers, scroll compensation, focus containment, and the modal stack.

  • Attached via {@attach modal(snippet, options)} or controlled programmatically with modal.open(), modal.close(), and modal.isOpen.
  • Top Layer or Contained: by default, renders via HTML5 popover="manual" directly in the browser's Top Layer (never clipped by ancestor overflow: hidden or transform). Optionally, pass container or portal: false to contain the modal within an embedded preview, canvas editor, or card.
  • Layout-shift-free scroll lock: measures window.innerWidth - document.documentElement.clientWidth and injects padding-right on body before locking body overflow, eliminating jitter on wide desktop displays.
  • Focus containment: automatically locates all tab-focusable elements, wraps focus between first and last elements on Tab and Shift+Tab, and restores focus to the trigger upon exit.
  • Multi-level stacking: nested modals push entries onto a reactive stack with calculated z-index increments. Escape and backdrop dismissal operate strictly on the topmost overlay.
  • Fluid animations: coordinates exit transitions with waitForAnimations() so dialogs and backdrop blurs complete before elements unmount.