import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { badgeClass } from '#components/ui/badge.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
drawerHeaderClass, drawerTitleClass, drawerDescriptionClass, drawerFooterClass,
} from '#components/ui/drawer.ts';
import {
fieldClass, fieldContentClass, fieldLabelClass, fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';
import { radioGroupClass, radioClass } from '#components/ui/radio-group.ts';
const deliveryTimes = [
{ value: 'asap', id: 'delivery-asap', label: 'Standard delivery', description: '25–35 min · Driver assigned now', badge: 'Fastest' },
{ value: '5-00', id: 'delivery-5-00', label: '5:00 PM – 5:15 PM', description: 'Prep starts at 4:45 PM' },
{ value: '5-30', id: 'delivery-5-30', label: '5:30 PM – 5:45 PM', description: "Good if you're heading home" },
{ value: '6-00', id: 'delivery-6-00', label: '6:00 PM – 6:15 PM', description: 'Most popular · High demand' },
{ value: '6-30', id: 'delivery-6-30', label: '6:30 PM – 6:45 PM', description: 'Last slot before kitchen closes' },
];
// shadcn slides it in from the right on a desktop and up from the bottom
// on a phone; the kit reads one direction, so this uses the desktop one.
// Each slot is a card whose whole <label> picks its radio. Confirming the
// slot (shadcn closes the drawer and shows a toast) is the reader's to wire.
export default function DrawerDemo() {
const deliveryTime = 'asap';
return html`
<ui-drawer>
<ui-drawer-trigger>
<button type="button" data-slot="button" data-variant="secondary" data-size="default" class=${buttonClass({ variant: 'secondary' })}>Open Drawer</button>
</ui-drawer-trigger>
<ui-drawer-content direction="right">
<div data-slot="drawer-header" class=${drawerHeaderClass()}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>Pick a delivery time</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>We'll prepare your order as soon as possible.</p>
</div>
<div class="flex-1 scroll-fade overflow-y-auto p-4">
<div role="radiogroup" aria-label="Delivery time" data-slot="radio-group" class=${cn(radioGroupClass(), 'gap-2')}>
${deliveryTimes.map((time) => html`
<label data-slot="field-label" for=${time.id} class=${fieldLabelClass()}>
<div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
<div data-slot="field-content" class=${fieldContentClass()}>
<div data-slot="field-label" class=${cn(fieldTitleClass(), 'flex items-center gap-2')}>
${time.label}
${time.badge ? html`<span data-slot="badge" data-variant="secondary" class=${badgeClass({ variant: 'secondary' })}>${time.badge}</span>` : ''}
</div>
<p data-slot="field-description" class=${fieldDescriptionClass()}>${time.description}</p>
</div>
<input type="radio" data-slot="radio" name="delivery-time" value=${time.value} id=${time.id} ?checked=${time.value === deliveryTime} class=${radioClass()}>
</div>
</label>
`)}
</div>
</div>
<div data-slot="drawer-footer" class=${drawerFooterClass()}>
<button type="button" data-slot="button" data-variant="default" data-size="default" class=${cn(buttonClass(), 'h-[34px]')}>Confirm Delivery Time</button>
<ui-drawer-close>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Cancel</button>
</ui-drawer-close>
</div>
</ui-drawer-content>
</ui-drawer>
`;
}
View Code
About
Drawer is built on the native <dialog> element, the same base as the Sheet: focus trap, Escape and backdrop close, focus restoration and scroll lock come from the platform. The drag handle and drag-to-dismiss run on Pointer Events, with no library.
Installation
Copy and paste the following code into your project.
/**
* Drawer: a panel that slides up from the bottom (or in from another edge)
* and can be dragged away, the mobile pattern shadcn builds on vaul. Tier-2.
* Like the sheet it IS a dialog: the native `<dialog>` opened with
* `showModal()`, its focus trap, Escape and backdrop close, focus
* restoration, scroll lock and label wiring. What the drawer adds is the
* drag handle and drag-to-dismiss on Pointer Events, with no library.
*
* shadcn parity:
* Drawer → <ui-drawer open>
* DrawerTrigger → <ui-drawer-trigger>
* DrawerContent (direction: bottom | top | left | right)
* → <ui-drawer-content direction="bottom">
* DrawerClose → <ui-drawer-close>
* DrawerHeader / DrawerFooter
* → <div class=${drawerHeaderClass()}> / <div class=${drawerFooterClass()}>
* DrawerTitle / DrawerDescription
* → <h2 data-slot="drawer-title" class=${drawerTitleClass()}> /
* <p data-slot="drawer-description" class=${drawerDescriptionClass()}>
*
* The panel carries `data-vaul-drawer-direction`, the attribute shadcn's
* drawer styles key on, so every ported style applies to it unchanged.
*
* Dragging the panel toward its edge moves it with the pointer; releasing it
* past a quarter of its size, or with a quick flick, closes the drawer, and
* anything less snaps it back. A drag never starts on a control inside the
* panel (a button, a field, a link), so those keep working.
*
* A11y (handled by the element, plus one obligation): the native `<dialog>`
* carries `role="dialog"`, is named by the `drawer-title` node and described
* by the `drawer-description` node, traps focus while open and returns it to
* the trigger. Dragging is a pointer convenience only; Escape, the backdrop
* and a close control are the ways everyone else closes it, so put a visible
* close button (a `<ui-drawer-close>` around a real `<button>`) in every
* drawer. The drag handle is decorative and hidden from assistive technology.
*
* @example
* ```html
* <ui-drawer>
* <ui-drawer-trigger><button class=${buttonClass({ variant: 'outline' })} type="button">Share</button></ui-drawer-trigger>
* <ui-drawer-content>
* <div class=${drawerHeaderClass()}>
* <h2 data-slot="drawer-title" class=${drawerTitleClass()}>Share this page</h2>
* </div>
* <div class=${drawerFooterClass()}>
* <ui-drawer-close><button class=${buttonClass({ variant: 'outline' })} type="button">Done</button></ui-drawer-close>
* </div>
* </ui-drawer-content>
* </ui-drawer>
* ```
*/
import { html } from '@webjsdev/core';
import { UiDialog, UiDialogTrigger, UiDialogContent, UiDialogClose } from './dialog.ts';
export type DrawerDirection = 'bottom' | 'top' | 'left' | 'right';
/** The visible panel. The element applies it; exported for a custom shell. */
export function drawerContentClass(): string {
return 'flex h-auto flex-col bg-background data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=left]:border-r group/drawer-content fixed z-50 data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm';
}
/** The drag handle at the top of a bottom drawer. The element renders it. */
/** The overlay behind the panel, which each style dims in its own way. */
export function drawerOverlayClass(): string {
return 'bg-black/50 fixed inset-0 z-50 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0';
}
export function drawerHandleClass(): string {
return 'mt-4 h-2 w-[100px] rounded-full bg-muted mx-auto hidden shrink-0 group-data-[vaul-drawer-direction=bottom]/drawer-content:block';
}
/** The title and description block. */
export function drawerHeaderClass(): string {
return 'gap-0.5 p-4 md:gap-1.5 md:text-start flex flex-col group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center';
}
/** The actions block, pushed to the bottom. */
export function drawerFooterClass(): string {
return 'gap-2 p-4 mt-auto flex flex-col';
}
/** The drawer's title. Mark it `data-slot="drawer-title"` so the drawer is named by it. */
export function drawerTitleClass(): string {
return 'font-semibold text-foreground cn-font-heading';
}
/** The drawer's description. Mark it `data-slot="drawer-description"`. */
export function drawerDescriptionClass(): string {
return 'text-sm text-muted-foreground';
}
export class UiDrawer extends UiDialog {
static rootTag = 'ui-drawer';
static contentTag = 'ui-drawer-content';
static slotPrefix = 'drawer';
}
UiDrawer.register('ui-drawer');
export class UiDrawerTrigger extends UiDialogTrigger {
static rootTag = 'ui-drawer';
static slotPrefix = 'drawer';
}
UiDrawerTrigger.register('ui-drawer-trigger');
export class UiDrawerClose extends UiDialogClose {
static rootTag = 'ui-drawer';
static slotPrefix = 'drawer';
}
UiDrawerClose.register('ui-drawer-close');
// A drag past this share of the panel's size closes the drawer, as does a
// release faster than FLICK pixels per millisecond toward the edge.
const CLOSE_RATIO = 0.25;
const FLICK = 0.5;
const NO_DRAG = 'button, a[href], input, select, textarea, [contenteditable=""], [contenteditable="true"], [role="button"], [role="slider"]';
export class UiDrawerContent extends UiDialogContent {
static rootTag = 'ui-drawer';
static slotPrefix = 'drawer';
#drag: { id: number; start: number; at: number; delta: number; panel: HTMLElement } | null = null;
// `direction` is read straight from the attribute, like the sheet's side:
// the element is built on the dialog's factory base and an author writes it
// once. Attribute reads work during server rendering, so the first paint
// already carries the direction.
_direction(): DrawerDirection {
const d = this.getAttribute?.('direction');
return d === 'top' || d === 'left' || d === 'right' ? d : 'bottom';
}
_drawerDirection(): DrawerDirection {
return this._direction();
}
_panelClass(): string {
return drawerContentClass();
}
_overlayClass(): string {
return drawerOverlayClass();
}
_panelLead(): unknown {
return html`<div data-slot="drawer-handle" aria-hidden="true" class=${drawerHandleClass()}></div>`;
}
// The drawer has no corner X: its handle, a close control the author places
// and Escape do that job, as in shadcn. Set in the constructor, which also
// runs during server rendering, so the first paint has no X to remove; an
// authored show-close-button attribute is applied after it and still wins.
constructor() {
super();
this.showCloseButton = 'false';
}
connectedCallback(): void {
super.connectedCallback?.();
this.addEventListener('pointerdown', this._onPointerDown);
}
disconnectedCallback(): void {
this.removeEventListener('pointerdown', this._onPointerDown);
super.disconnectedCallback?.();
}
/** +1 when moving toward the closing edge increases the coordinate. */
_axis(): { key: 'clientX' | 'clientY'; sign: 1 | -1; size: 'offsetWidth' | 'offsetHeight' } {
const d = this._direction();
if (d === 'top') return { key: 'clientY', sign: -1, size: 'offsetHeight' };
if (d === 'left') return { key: 'clientX', sign: -1, size: 'offsetWidth' };
if (d === 'right') return { key: 'clientX', sign: 1, size: 'offsetWidth' };
return { key: 'clientY', sign: 1, size: 'offsetHeight' };
}
_translate(delta: number): string {
const d = this._direction();
const v = d === 'top' || d === 'left' ? -delta : delta;
return d === 'left' || d === 'right' ? `translateX(${v}px)` : `translateY(${v}px)`;
}
_onPointerDown = (e: PointerEvent): void => {
if (e.button !== 0 || !this._parent()?.open) return;
const panel = this.querySelector<HTMLElement>('[data-slot="drawer-content"]');
const target = e.target as Element | null;
if (!panel || !target || !panel.contains(target)) return;
if (target.closest(NO_DRAG) && !target.closest('[data-slot="drawer-handle"]')) return;
const { key } = this._axis();
this.#drag = { id: e.pointerId, start: e[key], at: e.timeStamp, delta: 0, panel };
// Capture keeps the drag alive when the pointer leaves the panel. It throws
// for a pointer that is no longer active, which only costs that nicety.
try { panel.setPointerCapture(e.pointerId); } catch { /* not capturable */ }
panel.style.transition = 'none';
panel.addEventListener('pointermove', this._onPointerMove);
panel.addEventListener('pointerup', this._onPointerUp);
panel.addEventListener('pointercancel', this._onPointerUp);
};
_onPointerMove = (e: PointerEvent): void => {
const drag = this.#drag;
if (!drag || e.pointerId !== drag.id) return;
const { key, sign } = this._axis();
// Only movement toward the closing edge moves the panel.
drag.delta = Math.max(0, (e[key] - drag.start) * sign);
drag.panel.style.transform = this._translate(drag.delta);
};
_onPointerUp = (e: PointerEvent): void => {
const drag = this.#drag;
if (!drag || e.pointerId !== drag.id) return;
this.#drag = null;
const { panel, delta } = drag;
panel.removeEventListener('pointermove', this._onPointerMove);
panel.removeEventListener('pointerup', this._onPointerUp);
panel.removeEventListener('pointercancel', this._onPointerUp);
try { panel.releasePointerCapture(e.pointerId); } catch { /* already released */ }
const size = panel[this._axis().size] || 1;
const velocity = delta / Math.max(1, e.timeStamp - drag.at);
panel.style.transition = '';
panel.style.transform = '';
if (e.type !== 'pointercancel' && delta > 0 && (delta > size * CLOSE_RATIO || velocity > FLICK)) {
this._parent()?.hide();
}
};
}
UiDrawerContent.register('ui-drawer-content');
Update the import paths to match your project setup.
Usage
import {
drawerHeaderClass,
drawerTitleClass,
drawerDescriptionClass,
drawerFooterClass,
} from '#components/ui/drawer.ts';
<ui-drawer>
<ui-drawer-trigger>
<button type="button" class=${buttonClass({ variant: 'outline' })}>Open</button>
</ui-drawer-trigger>
<ui-drawer-content>
<div data-slot="drawer-header" class=${drawerHeaderClass()}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>Are you absolutely sure?</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>This action cannot be undone.</p>
</div>
<div data-slot="drawer-footer" class=${drawerFooterClass()}>
<button type="button" class=${buttonClass()}>Submit</button>
<ui-drawer-close>
<button type="button" class=${buttonClass({ variant: 'outline' })}>Cancel</button>
</ui-drawer-close>
</div>
</ui-drawer-content>
</ui-drawer>
Composition
Use the following composition to build a drawer:
ui-drawer
├── ui-drawer-trigger
└── ui-drawer-content
├── drawerHeaderClass()
│ ├── drawerTitleClass()
│ └── drawerDescriptionClass()
└── drawerFooterClass()
Scrollable Content
Keep actions visible while the content scrolls.
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import {
drawerHeaderClass, drawerTitleClass, drawerDescriptionClass, drawerFooterClass,
} from '#components/ui/drawer.ts';
export default function DrawerScrollableContent() {
return html`
<ui-drawer>
<ui-drawer-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Scrollable Content</button>
</ui-drawer-trigger>
<ui-drawer-content direction="right">
<div data-slot="drawer-header" class=${drawerHeaderClass()}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>Move Goal</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>Set your daily activity goal.</p>
</div>
<div class="no-scrollbar overflow-y-auto px-4">
${Array.from({ length: 10 }).map(() => html`
<p class="mb-4 leading-normal style-lyra:mb-2 style-lyra:leading-relaxed">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
`)}
</div>
<div data-slot="drawer-footer" class=${drawerFooterClass()}>
<button type="button" data-slot="button" data-variant="default" data-size="default" class=${buttonClass()}>Submit</button>
<ui-drawer-close>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Cancel</button>
</ui-drawer-close>
</div>
</ui-drawer-content>
</ui-drawer>
`;
}
View Code
Sides
Use the direction attribute on <ui-drawer-content> to set the side of the drawer. Available options are top, right, bottom, and left.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
drawerHeaderClass, drawerTitleClass, drawerDescriptionClass, drawerFooterClass,
} from '#components/ui/drawer.ts';
const DRAWER_SIDES = ['top', 'right', 'bottom', 'left'] as const;
export default function DrawerWithSides() {
return html`
<div class="flex flex-wrap gap-2">
${DRAWER_SIDES.map((side) => html`
<ui-drawer>
<ui-drawer-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${cn(buttonClass({ variant: 'outline' }), 'capitalize')}>${side}</button>
</ui-drawer-trigger>
<ui-drawer-content direction=${side} class="data-[vaul-drawer-direction=bottom]:max-h-[50vh] data-[vaul-drawer-direction=top]:max-h-[50vh]">
<div data-slot="drawer-header" class=${drawerHeaderClass()}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>Move Goal</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>
Set your daily activity goal.
</p>
</div>
<div class="no-scrollbar overflow-y-auto px-4">
${Array.from({ length: 10 }).map(() => html`
<p class="mb-4 leading-normal style-lyra:mb-2 style-lyra:leading-relaxed">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
`)}
</div>
<div data-slot="drawer-footer" class=${drawerFooterClass()}>
<button type="button" data-slot="button" data-variant="default" data-size="default" class=${buttonClass()}>Submit</button>
<ui-drawer-close>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Cancel</button>
</ui-drawer-close>
</div>
</ui-drawer-content>
</ui-drawer>
`)}
</div>
`;
}
View Code
Responsive Dialog
You can combine the Dialog and Drawer components to create a responsive dialog. This renders a Dialog on desktop and a Drawer on mobile. Both are in the page, and a breakpoint class shows one trigger and hides the other, so the first paint is already the right one.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
dialogHeaderClass, dialogTitleClass, dialogDescriptionClass,
} from '#components/ui/dialog.ts';
import {
drawerHeaderClass, drawerTitleClass, drawerDescriptionClass, drawerFooterClass,
} from '#components/ui/drawer.ts';
import { inputClass } from '#components/ui/input.ts';
import { labelClass } from '#components/ui/label.ts';
// shadcn picks Dialog or Drawer with a useMediaQuery hook. Here both are
// rendered and a breakpoint shows one trigger: the Dialog from md up, the
// Drawer below it. No script decides, so the first paint is already right.
function ProfileForm(id: string, className = '') {
return html`
<form class=${cn('grid items-start gap-6', className)}>
<div class="grid gap-3">
<label data-slot="label" for=${`email-${id}`} class=${labelClass()}>Email</label>
<input data-slot="input" type="email" id=${`email-${id}`} value="[email protected]" class=${inputClass()}>
</div>
<div class="grid gap-3">
<label data-slot="label" for=${`username-${id}`} class=${labelClass()}>Username</label>
<input data-slot="input" id=${`username-${id}`} value="@vivek" class=${inputClass()}>
</div>
<button type="submit" data-slot="button" data-variant="default" data-size="default" class=${buttonClass()}>Save changes</button>
</form>
`;
}
export default function DrawerDialogDemo() {
return html`
<div class="hidden md:contents">
<ui-dialog>
<ui-dialog-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Edit Profile</button>
</ui-dialog-trigger>
<ui-dialog-content class="sm:max-w-[425px]">
<div data-slot="dialog-header" class=${dialogHeaderClass()}>
<h2 data-slot="dialog-title" class=${dialogTitleClass()}>Edit profile</h2>
<p data-slot="dialog-description" class=${dialogDescriptionClass()}>
Make changes to your profile here. Click save when you're
done.
</p>
</div>
${ProfileForm('dialog')}
</ui-dialog-content>
</ui-dialog>
</div>
<div class="contents md:hidden">
<ui-drawer>
<ui-drawer-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Edit Profile</button>
</ui-drawer-trigger>
<ui-drawer-content>
<div data-slot="drawer-header" class=${cn(drawerHeaderClass(), 'text-left')}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>Edit profile</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>
Make changes to your profile here. Click save when you're done.
</p>
</div>
${ProfileForm('drawer', 'px-4')}
<div data-slot="drawer-footer" class=${cn(drawerFooterClass(), 'pt-2')}>
<ui-drawer-close>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Cancel</button>
</ui-drawer-close>
</div>
</ui-drawer-content>
</ui-drawer>
</div>
`;
}
View Code
RTL
To enable RTL support, see the RTL configuration guide.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
drawerHeaderClass, drawerTitleClass, drawerDescriptionClass, drawerFooterClass,
} from '#components/ui/drawer.ts';
import { MinusIcon, PlusIcon } from '#lib/ui/lucide.ts';
const data = [
{ goal: 400 },
{ goal: 300 },
{ goal: 200 },
{ goal: 300 },
{ goal: 200 },
{ goal: 278 },
{ goal: 189 },
{ goal: 239 },
{ goal: 300 },
{ goal: 200 },
{ goal: 278 },
{ goal: 189 },
{ goal: 349 },
];
const translations = {
en: {
dir: 'ltr',
locale: 'en-US',
values: {
trigger: 'Open Drawer',
title: 'Move Goal',
description: 'Set your daily activity goal.',
caloriesPerDay: 'Calories/day',
decrease: 'Decrease',
increase: 'Increase',
submit: 'Submit',
cancel: 'Cancel',
},
},
ar: {
dir: 'rtl',
locale: 'ar-EG',
values: {
trigger: 'فتح الدرج',
title: 'نقل الهدف',
description: 'حدد هدف نشاطك اليومي.',
caloriesPerDay: 'سعرات حرارية/يوم',
decrease: 'تقليل',
increase: 'زيادة',
submit: 'إرسال',
cancel: 'إلغاء',
},
},
he: {
dir: 'rtl',
locale: 'he-IL',
values: {
trigger: 'פתח מגירה',
title: 'הזז מטרה',
description: 'הגדר את יעד הפעילות היומי שלך.',
caloriesPerDay: 'קלוריות/יום',
decrease: 'הקטן',
increase: 'הגדל',
submit: 'שלח',
cancel: 'בטל',
},
},
};
// The bars are plain elements sized from the data, standing in for the
// Recharts BarChart shadcn's demo draws, in reading order for the direction.
export default function DrawerRtl() {
const lang = 'ar';
const { dir, locale, values: t } = translations[lang];
const goal = 350;
return html`
<ui-drawer>
<ui-drawer-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>${t.trigger}</button>
</ui-drawer-trigger>
<ui-drawer-content dir=${dir} lang=${lang}>
<div class="mx-auto w-full max-w-sm">
<div data-slot="drawer-header" class=${drawerHeaderClass()}>
<h2 data-slot="drawer-title" class=${drawerTitleClass()}>${t.title}</h2>
<p data-slot="drawer-description" class=${drawerDescriptionClass()}>${t.description}</p>
</div>
<div class="p-4 pb-0">
<div class="flex items-center justify-center space-x-2">
<button type="button" data-slot="button" data-variant="outline" data-size="icon" ?disabled=${goal <= 200} class=${cn(buttonClass({ variant: 'outline', size: 'icon' }), 'h-8 w-8 shrink-0 rounded-full')}>
${MinusIcon()}
<span class="sr-only">${t.decrease}</span>
</button>
<div class="flex-1 text-center">
<div class="text-7xl font-bold tracking-tighter">${goal.toLocaleString(locale)}</div>
<div class="text-[0.70rem] text-muted-foreground uppercase">${t.caloriesPerDay}</div>
</div>
<button type="button" data-slot="button" data-variant="outline" data-size="icon" ?disabled=${goal >= 400} class=${cn(buttonClass({ variant: 'outline', size: 'icon' }), 'h-8 w-8 shrink-0 rounded-full')}>
${PlusIcon()}
<span class="sr-only">${t.increase}</span>
</button>
</div>
<div class="mt-3 h-[120px]">
<div aria-hidden="true" class="flex h-full items-end gap-1 p-1">
${data.map((d) => html`<div class="flex-1 bg-chart-2" style=${'height: ' + (d.goal / 400) * 100 + '%'}></div>`)}
</div>
</div>
</div>
<div data-slot="drawer-footer" class=${drawerFooterClass()}>
<button type="button" data-slot="button" data-variant="default" data-size="default" class=${buttonClass()}>${t.submit}</button>
<ui-drawer-close>
<button type="button" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>${t.cancel}</button>
</ui-drawer-close>
</div>
</div>
</ui-drawer-content>
</ui-drawer>
`;
}
View Code
API Reference
The drawer is a native <dialog> opened with showModal(), so it traps focus, closes on Escape and on the backdrop, returns focus to the trigger and locks page scroll. On top of that it adds a drag handle and drag-to-dismiss on Pointer Events, with no library: releasing the panel past a quarter of its size, or with a quick flick toward its edge, closes it. A drag never starts on a control inside the panel.
ui-drawer
The root. It tracks the open state.
It dispatches ui-open-change with { detail: { open } } after the drawer opens or closes, and has .show(), .hide() and .toggle() methods.
ui-drawer-trigger
Wraps the control that opens the drawer. Put a real <button> inside it.
ui-drawer-content
The panel. It renders the drag handle on a bottom drawer and carries data-vaul-drawer-direction, the attribute the drawer styles key on. Classes you put on it are applied to the panel.
ui-drawer-close
Wraps a control that closes the drawer. Dragging is a pointer convenience only, so put a visible close button in every drawer.