Dimensions
Set the dimensions for the layer.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { inputClass } from '#components/ui/input.ts';
import { labelClass } from '#components/ui/label.ts';
import { popoverContentClass } from '#components/ui/popover.ts';
const field = (id: string, label: string, value: string) => html`
<div class="grid grid-cols-3 items-center gap-4">
<label data-slot="label" for=${id} class=${labelClass()}>${label}</label>
<input data-slot="input" id=${id} value=${value} class=${cn(inputClass(), 'col-span-2 h-8')}>
</div>
`;
export default function PopoverDemo() {
return html`
<button type="button" popovertarget="popover-demo" aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Open popover</button>
<div id="popover-demo" popover role="dialog" aria-labelledby="popover-demo-title" data-slot="popover-content" data-side="bottom" data-align="center" class=${cn(popoverContentClass(), 'w-80')}>
<div class="grid gap-4">
<div class="space-y-2">
<h4 id="popover-demo-title" class="leading-none font-medium">Dimensions</h4>
<p class="text-sm text-muted-foreground">
Set the dimensions for the layer.
</p>
</div>
<div class="grid gap-2">
${field('width', 'Width', '100%')}
${field('maxWidth', 'Max. width', '300px')}
${field('height', 'Height', '25px')}
${field('maxHeight', 'Max. height', 'none')}
</div>
</div>
</div>
`;
}
View Code
Installation
Copy and paste the following code into your project.
/**
* Popover: floating panel anchored to a trigger button, built on the
* native HTML Popover API (`popover` attribute + `popovertarget`).
*
* Tier-1 (no custom element). The browser handles open / close state,
* top-layer rendering, light-dismiss on outside click (with
* `popover="auto"`), Escape-to-close, focus restoration to the invoker,
* and CSS Anchor Positioning's implicit anchor (a popover invoked via
* `popovertarget` is automatically anchored to its invoker, no
* `anchor-name` / `position-anchor` inline style needed for the common
* case). CSS Anchor Positioning ships in Chrome 125+, Safari 26+,
* Firefox 134+.
*
* shadcn parity:
* Popover → <button popovertarget="id"> + <div id="id" popover>
* PopoverContent → popoverContentClass({ side, align, sideOffset, alignOffset })
* PopoverHeader → popoverHeaderClass()
* PopoverTitle → popoverTitleClass()
* PopoverDescription → popoverDescriptionClass()
*
* Measured placement, where CSS Anchor Positioning isn't enough, is
* `positionFloating` in `floating.ts` (the Tier-2 tooltip / hover-card /
* dropdown-menu components use it). It lives apart so these class helpers stay
* free of browser code. Migrated from the prior <ui-popover> custom element set.
*
* Design tokens used: --popover, --popover-foreground, --border.
*
* A11y (required for accessible output):
* This is the Tier-1 component with the most for you to supply, because
* `popoverContentClass()` returns only classes: the panel it styles is a bare
* `<div popover>` with NO role and NO accessible name unless you add them.
* GIVE THE PANEL `role="dialog"`, then NAME it with `aria-labelledby`
* pointing at the `popoverTitleClass()` heading's `id`. Both halves matter: a
* role with no name announces as a bare "dialog", and a name with no role is
* never announced as a grouped thing at all. This is what shadcn's
* `PopoverContent` does for you in React, and here it is yours.
* Point `aria-describedby` at the `popoverDescriptionClass()` paragraph when
* there is one, so the supporting line is announced with the panel.
* TELL THE TRIGGER what it does: `aria-expanded` tracking the open state, and
* `aria-haspopup="dialog"`. The browser does not derive either from
* `popovertarget`, so without them the button announces as a plain button that
* gives no hint a panel will appear. Keep `aria-expanded` in sync from the
* panel's `toggle` event, which is the native signal for this.
* Use `popover` (auto), not `popover="manual"`, unless you have a reason.
* The auto mode is where the platform gives you light-dismiss, Escape-to-close,
* and FOCUS RESTORATION back to the invoker; manual mode gives up all three
* and makes them your problem.
* Make the title a REAL heading element (`<h2>` / `<h3>`) at the right level
* for its place in the page, not a styled `<div>`, so it appears in the
* heading outline a screen reader user navigates by.
*
* @example
* ```html
* <!-- Single invoker, implicit anchor, zero inline style. -->
* <button popovertarget="filter" aria-expanded="false" aria-haspopup="dialog"
* class=${buttonClass({ variant: 'outline' })}>Filter</button>
* <div id="filter" popover role="dialog" aria-labelledby="filter-title"
* aria-describedby="filter-desc"
* class=${popoverContentClass({ side: 'bottom', align: 'start', sideOffset: 4 })}>
* <div class=${popoverHeaderClass()}>
* <h3 class=${popoverTitleClass()} id="filter-title">Filter posts</h3>
* <p class=${popoverDescriptionClass()} id="filter-desc">By tag and status.</p>
* </div>
* </div>
*
* <!-- Keep the trigger's aria-expanded in sync from the native toggle event. -->
* <script type="module">
* const panel = document.getElementById('filter');
* const trigger = document.querySelector('[popovertarget="filter"]');
* panel.addEventListener('toggle', (e) => {
* trigger.setAttribute('aria-expanded', String(e.newState === 'open'));
* });
* </script>
*
* <!-- Explicit anchor, for multiple invokers or anchoring to a different element. -->
* <span style="anchor-name: --picker">@vivek</span>
* <button popovertarget="profile" aria-expanded="false" aria-haspopup="dialog">Show</button>
* <div id="profile" popover role="dialog" aria-labelledby="profile-title"
* style="position-anchor: --picker"
* class=${popoverContentClass({ side: 'bottom' })}>
* <div class=${popoverHeaderClass()}>
* <h3 class=${popoverTitleClass()} id="profile-title">Vivek Khandelwal</h3>
* <p class=${popoverDescriptionClass()}>@vivek</p>
* </div>
* </div>
* ```
*/
// --------------------------------------------------------------------------
// Class helpers
// --------------------------------------------------------------------------
/**
* Popover content options, mirror shadcn's `<PopoverContent>` props.
* `side` and `align` map to CSS Anchor Positioning's `position-area`;
* `sideOffset` maps to a directional margin so the popover sits a few
* pixels off the anchor's edge.
*
* `sideOffset` is restricted to a discrete set so Tailwind 4's static
* scanner sees each emitted class literal. For arbitrary values,
* override the margin via inline style on the popover element.
*/
export type PopoverSideOffset = 0 | 2 | 4 | 6 | 8 | 12 | 16 | 20 | 24;
type PopoverAlignStep = 0 | 2 | 4 | 6 | 8 | 12 | 16 | 20 | 24;
/** An align offset in pixels, either way: a negative one pulls back past the aligned edge. */
export type PopoverAlignOffset = PopoverAlignStep | -2 | -4 | -6 | -8 | -12 | -16 | -20 | -24;
export interface PopoverContentOptions {
/** Which side of the trigger the popover appears on. Default 'bottom'. */
side?: PopoverSide;
/** Alignment along the chosen side. Default 'center'. */
align?: PopoverAlign;
/** Pixels between the trigger and the popover. Default 4 (shadcn default). */
sideOffset?: PopoverSideOffset;
/**
* Pixels offset along the align axis. Positive values push away from
* the aligned edge toward the opposite edge, negative ones the other way
* (shadcn's `alignOffset={-4}`). No-op for align='center'. Default 0
* (matches shadcn).
*/
alignOffset?: PopoverAlignOffset;
}
// position-area combinations baked as literal class strings so Tailwind 4's
// scanner generates CSS for every (side, align) pair the helper can return.
// Underscores become spaces in arbitrary CSS values.
const POSITION_AREA_CLASS: Record<string, string> = {
'top-start': '[position-area:top_span-right]',
'top-center': '[position-area:top]',
'top-end': '[position-area:top_span-left]',
'bottom-start': '[position-area:bottom_span-right]',
'bottom-center': '[position-area:bottom]',
'bottom-end': '[position-area:bottom_span-left]',
'left-start': '[position-area:left_span-bottom]',
'left-center': '[position-area:left]',
'left-end': '[position-area:left_span-top]',
'right-start': '[position-area:right_span-bottom]',
'right-center': '[position-area:right]',
'right-end': '[position-area:right_span-top]',
};
// Align-axis translate classes. For align='start', positive offset moves
// the popover AWAY from the start edge (toward the end edge); align='end'
// reverses. align='center' is a no-op. The axis is perpendicular to the
// side: top/bottom sides translate X; left/right sides translate Y.
// All 36 (4 axis-direction combos × 9 offset values) appear literally so
// Tailwind 4 generates each class.
const ALIGN_OFFSET_CLASS: Record<string, Record<PopoverAlignStep, string>> = {
'horizontal-start': {
0: 'translate-x-[0px]', 2: 'translate-x-[2px]', 4: 'translate-x-[4px]',
6: 'translate-x-[6px]', 8: 'translate-x-[8px]', 12: 'translate-x-[12px]',
16: 'translate-x-[16px]', 20: 'translate-x-[20px]', 24: 'translate-x-[24px]',
},
'horizontal-end': {
0: 'translate-x-[0px]', 2: 'translate-x-[-2px]', 4: 'translate-x-[-4px]',
6: 'translate-x-[-6px]', 8: 'translate-x-[-8px]', 12: 'translate-x-[-12px]',
16: 'translate-x-[-16px]', 20: 'translate-x-[-20px]', 24: 'translate-x-[-24px]',
},
'vertical-start': {
0: 'translate-y-[0px]', 2: 'translate-y-[2px]', 4: 'translate-y-[4px]',
6: 'translate-y-[6px]', 8: 'translate-y-[8px]', 12: 'translate-y-[12px]',
16: 'translate-y-[16px]', 20: 'translate-y-[20px]', 24: 'translate-y-[24px]',
},
'vertical-end': {
0: 'translate-y-[0px]', 2: 'translate-y-[-2px]', 4: 'translate-y-[-4px]',
6: 'translate-y-[-6px]', 8: 'translate-y-[-8px]', 12: 'translate-y-[-12px]',
16: 'translate-y-[-16px]', 20: 'translate-y-[-20px]', 24: 'translate-y-[-24px]',
},
};
// Per-side offset margin classes. Side 'bottom' wants margin-top, etc.
// Each value of PopoverSideOffset appears literally for Tailwind's scanner.
const MARGIN_OFFSET_CLASS: Record<PopoverSide, Record<PopoverSideOffset, string>> = {
top: {
0: '[margin-bottom:0px]', 2: '[margin-bottom:2px]', 4: '[margin-bottom:4px]',
6: '[margin-bottom:6px]', 8: '[margin-bottom:8px]', 12: '[margin-bottom:12px]',
16: '[margin-bottom:16px]', 20: '[margin-bottom:20px]', 24: '[margin-bottom:24px]',
},
bottom: {
0: '[margin-top:0px]', 2: '[margin-top:2px]', 4: '[margin-top:4px]',
6: '[margin-top:6px]', 8: '[margin-top:8px]', 12: '[margin-top:12px]',
16: '[margin-top:16px]', 20: '[margin-top:20px]', 24: '[margin-top:24px]',
},
left: {
0: '[margin-right:0px]', 2: '[margin-right:2px]', 4: '[margin-right:4px]',
6: '[margin-right:6px]', 8: '[margin-right:8px]', 12: '[margin-right:12px]',
16: '[margin-right:16px]', 20: '[margin-right:20px]', 24: '[margin-right:24px]',
},
right: {
0: '[margin-left:0px]', 2: '[margin-left:2px]', 4: '[margin-left:4px]',
6: '[margin-left:6px]', 8: '[margin-left:8px]', 12: '[margin-left:12px]',
16: '[margin-left:16px]', 20: '[margin-left:20px]', 24: '[margin-left:24px]',
},
};
/**
* Popover content class. `side` and `align` cover the shadcn
* `<PopoverContent>` placement props; `sideOffset` sets the gap to
* the anchor. The visual layer (border, bg, padding, shadow) is
* fixed to match shadcn's default; width is opinionated at `w-72`
* (override at the call site).
*
* `m-0` clears the UA `margin: auto` so anchor positioning isn't
* fighting auto-centering, then a single directional margin sets the
* sideOffset gap.
*
* `not-open:hidden` keeps a CLOSED panel hidden. The browser hides one
* through its own `[popover]:not(:popover-open) { display: none }`, but
* that is a user-agent rule, which any author `display` beats, and most
* styles give the panel `flex` (shadcn's Radix content is never in the
* document while closed, so its styles never had to care). Every
* `popover` panel in the kit carries the same guard.
*/
export function popoverContentClass(opts: PopoverContentOptions = {}): string {
const side = opts.side ?? 'bottom';
const align = opts.align ?? 'center';
const sideOffset = opts.sideOffset ?? 4;
const alignOffset = opts.alignOffset ?? 0;
// align='center' has no align axis to offset along, skip the translate.
let alignClass = '';
if (align !== 'center' && alignOffset !== 0) {
const axis = side === 'top' || side === 'bottom' ? 'horizontal' : 'vertical';
// A negative offset from one edge is the same shift as a positive one
// from the other, so it reads the other edge's table.
const edge = alignOffset < 0 ? (align === 'start' ? 'end' : 'start') : align;
alignClass = ALIGN_OFFSET_CLASS[`${axis}-${edge}`][Math.abs(alignOffset) as PopoverAlignStep] ?? '';
}
return [
'm-0 rounded-md border bg-popover p-4 text-popover-foreground shadow-md z-50 w-72 origin-(--radix-popover-content-transform-origin) outline-hidden not-open:hidden',
POSITION_AREA_CLASS[`${side}-${align}`],
MARGIN_OFFSET_CLASS[side][sideOffset],
alignClass,
].filter(Boolean).join(' ');
}
export const popoverHeaderClass = (): string => 'flex flex-col gap-1 text-sm';
export const popoverTitleClass = (): string => 'font-medium';
export const popoverDescriptionClass = (): string => 'text-muted-foreground';
// --------------------------------------------------------------------------
// Placement. positionFloating lives in floating.ts (import it from there),
// since it reads the window and the elements' boxes. This module is the class
// helpers alone, so a page importing them reaches no browser code and the
// framework can drop it from the browser. It does not re-export
// positionFloating either: a re-export is an import, and the page would reach
// that code through it all the same.
// --------------------------------------------------------------------------
export type PopoverSide = 'top' | 'bottom' | 'left' | 'right';
export type PopoverAlign = 'start' | 'center' | 'end';
Update the import paths to match your project setup.
Usage
import { buttonClass } from '#components/ui/button.ts';
import {
popoverContentClass,
popoverDescriptionClass,
popoverHeaderClass,
popoverTitleClass,
} from '#components/ui/popover.ts';
<button
popovertarget="popover"
aria-haspopup="dialog"
aria-expanded="false"
class=${buttonClass({ variant: 'outline' })}
>
Open Popover
</button>
<div
id="popover"
popover
role="dialog"
aria-labelledby="popover-title"
class=${popoverContentClass()}
>
<div class=${popoverHeaderClass()}>
<h3 id="popover-title" class=${popoverTitleClass()}>Title</h3>
<p class=${popoverDescriptionClass()}>Description text here.</p>
</div>
</div>
Composition
Use the following composition to build a popover:
button popovertarget="id"
div popover id="id" popoverContentClass()
└── div popoverHeaderClass()
├── h3 popoverTitleClass()
└── p popoverDescriptionClass()
The popover is the browser's own Popover API. The popovertarget button opens the panel, which renders in the top layer, closes on an outside click or Escape, returns focus to the button, and is anchored to the button by CSS Anchor Positioning, all with no script.
Basic
A simple popover with a header, title, and description.
Dimensions
Set the dimensions for the layer.
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import {
popoverContentClass, popoverHeaderClass, popoverTitleClass, popoverDescriptionClass,
} from '#components/ui/popover.ts';
export default function PopoverBasic() {
return html`
<button type="button" popovertarget="popover-basic" aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Open Popover</button>
<div id="popover-basic" popover role="dialog" aria-labelledby="popover-basic-title" aria-describedby="popover-basic-description" data-slot="popover-content" data-side="bottom" data-align="start" class=${popoverContentClass({ align: 'start' })}>
<div data-slot="popover-header" class=${popoverHeaderClass()}>
<h3 id="popover-basic-title" data-slot="popover-title" class=${popoverTitleClass()}>Dimensions</h3>
<p id="popover-basic-description" data-slot="popover-description" class=${popoverDescriptionClass()}>
Set the dimensions for the layer.
</p>
</div>
</div>
`;
}
View Code
Align
Use the align option of popoverContentClass() to control the horizontal alignment.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { popoverContentClass, type PopoverAlign } from '#components/ui/popover.ts';
const aligned = (align: PopoverAlign, label: string, text: string) => {
const id = 'popover-align-' + align;
return html`
<button type="button" popovertarget=${id} aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="sm" class=${buttonClass({ variant: 'outline', size: 'sm' })}>
${label}
</button>
<div id=${id} popover role="dialog" aria-label=${text} data-slot="popover-content" data-side="bottom" data-align=${align} class=${cn(popoverContentClass({ align }), 'w-40')}>
${text}
</div>
`;
};
export default function PopoverAlignments() {
return html`
<div class="flex gap-6">
${aligned('start', 'Start', 'Aligned to start')}
${aligned('center', 'Center', 'Aligned to center')}
${aligned('end', 'End', 'Aligned to end')}
</div>
`;
}
View Code
With Form
A popover with form fields inside.
Dimensions
Set the dimensions for the layer.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';
import { inputClass } from '#components/ui/input.ts';
import {
popoverContentClass, popoverHeaderClass, popoverTitleClass, popoverDescriptionClass,
} from '#components/ui/popover.ts';
const field = (id: string, label: string, value: string) => html`
<div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
<label data-slot="field-label" for=${id} class=${cn(fieldLabelClass(), 'w-1/2')}>${label}</label>
<input data-slot="input" id=${id} value=${value} class=${inputClass()}>
</div>
`;
export default function PopoverForm() {
return html`
<button type="button" popovertarget="popover-form" aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>Open Popover</button>
<div id="popover-form" popover role="dialog" aria-labelledby="popover-form-title" aria-describedby="popover-form-description" data-slot="popover-content" data-side="bottom" data-align="start" class=${cn(popoverContentClass({ align: 'start' }), 'w-64')}>
<div data-slot="popover-header" class=${popoverHeaderClass()}>
<h3 id="popover-form-title" data-slot="popover-title" class=${popoverTitleClass()}>Dimensions</h3>
<p id="popover-form-description" data-slot="popover-description" class=${popoverDescriptionClass()}>
Set the dimensions for the layer.
</p>
</div>
<div data-slot="field-group" class=${cn(fieldGroupClass(), 'gap-4')}>
${field('popover-form-width', 'Width', '100%')}
${field('popover-form-height', 'Height', '25px')}
</div>
</div>
`;
}
View Code
RTL
To enable RTL support, see the RTL configuration guide.
الأبعاد
تعيين الأبعاد للطبقة.
الأبعاد
تعيين الأبعاد للطبقة.
الأبعاد
تعيين الأبعاد للطبقة.
الأبعاد
تعيين الأبعاد للطبقة.
import { html } from '@webjsdev/core';
import { buttonClass } from '#components/ui/button.ts';
import {
popoverContentClass, popoverHeaderClass, popoverTitleClass, popoverDescriptionClass,
type PopoverSide,
} from '#components/ui/popover.ts';
const translations = {
en: {
dir: 'ltr',
values: {
title: 'Dimensions',
description: 'Set the dimensions for the layer.',
left: 'Left',
top: 'Top',
bottom: 'Bottom',
right: 'Right',
},
},
ar: {
dir: 'rtl',
values: {
title: 'الأبعاد',
description: 'تعيين الأبعاد للطبقة.',
left: 'يسار',
top: 'أعلى',
bottom: 'أسفل',
right: 'يمين',
},
},
he: {
dir: 'rtl',
values: {
title: 'מימדים',
description: 'הגדר את המימדים לשכבה.',
left: 'שמאל',
top: 'למעלה',
bottom: 'למטה',
right: 'ימין',
},
},
};
const physicalSides: PopoverSide[] = ['left', 'top', 'bottom', 'right'];
// The provider is the dir attribute on each panel, as in shadcn's demo.
export default function PopoverRtl() {
const lang = 'ar';
const { dir, values: t } = translations[lang];
const sidePopover = (side: PopoverSide) => {
const id = 'popover-rtl-' + side;
return html`
<button type="button" popovertarget=${id} aria-haspopup="dialog" aria-expanded="false" data-slot="button" data-variant="outline" data-size="default" class=${buttonClass({ variant: 'outline' })}>${t[side]}</button>
<div id=${id} popover role="dialog" dir=${dir} lang=${lang} aria-labelledby=${id + '-title'} data-slot="popover-content" data-side=${side} data-align="center" class=${popoverContentClass({ side })}>
<div data-slot="popover-header" class=${popoverHeaderClass()}>
<h3 id=${id + '-title'} data-slot="popover-title" class=${popoverTitleClass()}>${t.title}</h3>
<p data-slot="popover-description" class=${popoverDescriptionClass()}>${t.description}</p>
</div>
</div>
`;
};
return html`
<div class="flex flex-wrap justify-center gap-2">
${physicalSides.map(sidePopover)}
</div>
`;
}
View Code
API Reference
popoverContentClass
popoverContentClass() returns the classes for the panel, a <div popover> opened by a button whose popovertarget names its id. Placement is CSS Anchor Positioning, so the options are a fixed set the stylesheet carries. For any other offset, set the margin inline.
Header, Title, Description
popoverHeaderClass(), popoverTitleClass() and popoverDescriptionClass() take no options. Make the title a real heading at the right level for its place in the page.
Accessibility
A class helper returns only classes, so the panel's role and name are yours to supply. Give the panel role="dialog" and name it with aria-labelledby pointing at the title, and aria-describedby pointing at the description when there is one. Give the button aria-haspopup="dialog" and an aria-expanded kept in sync from the panel's native toggle event.
const panel = document.getElementById('popover');
const trigger = document.querySelector('[popovertarget="popover"]');
panel.addEventListener('toggle', (e) => {
trigger.setAttribute('aria-expanded', String(e.newState === 'open'));
});