View as Markdown

Popover

A click-triggered popup that displays rich content, anchored to its trigger.

100%
Loading...
<div class="flex items-start justify-center pt-6" style="min-height: 400px">
    <twig:Popover>
        <twig:Popover:Trigger>
            <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>Open Popover</twig:Button>
        </twig:Popover:Trigger>
        <twig:Popover:Content align="start" class="w-80">
            <div class="grid gap-4">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">Dimensions</h4>
                    <p class="text-xs text-muted-foreground">Set the dimensions for the layer.</p>
                </div>
                <div class="grid gap-2">
                    <div class="grid grid-cols-3 items-center gap-4">
                        <twig:Label for="demo-width">Width</twig:Label>
                        <input id="demo-width" class="col-span-2 h-8 rounded-md border px-2 text-sm" value="100%">
                    </div>
                    <div class="grid grid-cols-3 items-center gap-4">
                        <twig:Label for="demo-max-width">Max. width</twig:Label>
                        <input id="demo-max-width" class="col-span-2 h-8 rounded-md border px-2 text-sm" value="300px">
                    </div>
                    <div class="grid grid-cols-3 items-center gap-4">
                        <twig:Label for="demo-height">Height</twig:Label>
                        <input id="demo-height" class="col-span-2 h-8 rounded-md border px-2 text-sm" value="25px">
                    </div>
                    <div class="grid grid-cols-3 items-center gap-4">
                        <twig:Label for="demo-max-height">Max. height</twig:Label>
                        <input id="demo-max-height" class="col-span-2 h-8 rounded-md border px-2 text-sm" value="none">
                    </div>
                </div>
            </div>
        </twig:Popover:Content>
    </twig:Popover>
</div>

Installation

Note

Available since UX Toolkit 3.5.

php bin/console ux:install popover --kit shadcn

Install the following Composer dependencies:

composer require twig/extra-bundle twig/html-extra:^3.24.0 symfony/ux-twig-component:^3.5 tales-from-a-dev/twig-tailwind-extra:^1.3.0

Install the following front-end dependencies:

npm install shadcn tw-animate-css
# ...or with Symfony AssetMapper
php bin/console importmap:require tw-animate-css/dist/tw-animate.css shadcn/dist/tailwind.css

Copy the following file(s) into your app:

assets/controllers/popover_controller.js
import { Controller } from '@hotwired/stimulus';

// The native path needs both: a popover without anchor positioning would be centred by the browser.
const native = HTMLElement.prototype.hasOwnProperty('popover') && CSS.supports('position-area', 'block-end');
let anchors = 0;

export default class extends Controller {
    static targets = ['trigger', 'content'];

    static values = {
        open: { type: Boolean, default: false },
        name: { type: String, default: '' },
    };

    #connected = false;
    #anchor = `--popover-${++anchors}`;

    connect() {
        this.updateState();
        this.#connected = true;
    }

    disconnect() {
        this.#connected = false;
    }

    contentTargetConnected(content) {
        if (!native) {
            return;
        }
        this.#connectNative(content);
        content.addEventListener('beforetoggle', this.#onBeforeToggle);
        content.addEventListener('toggle', this.#onToggle);
    }

    contentTargetDisconnected(content) {
        if (!native) {
            return;
        }
        content.removeEventListener('beforetoggle', this.#onBeforeToggle);
        content.removeEventListener('toggle', this.#onToggle);
        content.removeAttribute('popover');
        content.style.removeProperty('position-anchor');
        content.style.removeProperty('transform-origin');
        this.element.style.removeProperty('anchor-name');
    }

    toggle(event) {
        event?.preventDefault();
        this.openValue = !this.openValue;
    }

    close() {
        this.openValue = false;
    }

    openValueChanged() {
        if (native && this.hasContentTarget) {
            this.#toggleNative(this.contentTarget);
        } else {
            this.updateState();
        }

        if (!this.openValue) {
            return;
        }

        if (this.nameValue) {
            window.dispatchEvent(
                new CustomEvent('popover:open', {
                    detail: { name: this.nameValue, source: this.element },
                })
            );
        }

        // Skip on initial render so an `open` popover does not steal focus on page load.
        if (this.#connected) {
            this.#focusContent();
        }
    }

    handleGroupOpen(event) {
        if (!this.nameValue || !this.openValue) {
            return;
        }
        if (event.detail.name !== this.nameValue || event.detail.source === this.element) {
            return;
        }
        this.openValue = false;
    }

    handleOutsideClick(event) {
        if (!this.openValue || this.element.contains(event.target)) {
            return;
        }
        this.openValue = false;
    }

    handleEscape(event) {
        if (!this.openValue || event.key !== 'Escape') {
            return;
        }
        this.openValue = false;
        this.triggerTargets[0]?.focus();
    }

    updateState(open = this.openValue) {
        const state = open ? 'open' : 'closed';

        this.element.dataset.state = state;

        for (const trigger of this.triggerTargets) {
            trigger.setAttribute('aria-expanded', String(open));
            trigger.dataset.state = state;
        }

        for (const content of this.contentTargets) {
            content.dataset.state = state;
            content.setAttribute('aria-hidden', String(!open));
        }
    }

    // Idempotent, as a Turbo morph strips what it sets.
    #connectNative(content) {
        if ('manual' !== content.popover) {
            // Without a transition, so a closed popover goes straight to `display: none`.
            content.style.transition = 'none';
            // `manual`: the browser's light dismiss would also close it on a click elsewhere in the root.
            content.popover = 'manual';
            content.getBoundingClientRect();
            content.style.removeProperty('transition');
        }
        content.style.positionAnchor = this.#anchor;
        this.element.style.setProperty('anchor-name', this.#anchor);
    }

    #toggleNative(content) {
        this.#connectNative(content);
        if (content.matches(':popover-open') !== this.openValue) {
            content.togglePopover(this.openValue);
        }
        if (this.openValue) {
            this.#placeTransformOrigin(content);
        }
    }

    // The browser can flip the content to the other side of its anchor, so it grows from the edge next to it.
    #placeTransformOrigin(content) {
        const box = content.getBoundingClientRect();
        const anchor = this.element.getBoundingClientRect();
        const x = Math.min(Math.max((anchor.left + anchor.width / 2 - box.left) / box.width, 0), 1);
        const y = Math.min(Math.max((anchor.top + anchor.height / 2 - box.top) / box.height, 0), 1);
        content.style.transformOrigin = `${x * 100}% ${y * 100}%`;
    }

    // Updates the state before the browser shows or hides the content, so the exit transition can play.
    #onBeforeToggle = (event) => {
        if ('closed' === event.newState) {
            this.#placeTransformOrigin(event.target);
        }
        this.updateState('open' === event.newState);
    };

    #onToggle = (event) => {
        this.openValue = 'open' === event.newState;
    };

    #focusContent() {
        const content = this.contentTargets[0];
        const focusable =
            content?.querySelector('[autofocus]:not([disabled])') ??
            content?.querySelector(
                'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])'
            );
        if (!focusable) {
            return;
        }

        // `visibility` is transitioned, so the content stays `visibility: hidden` (not
        // focusable) for at least one frame after opening, and longer on a busy browser.
        const focusWhenVisible = () => {
            if (!this.openValue) {
                return;
            }
            focusable.focus();
            if (document.activeElement !== focusable) {
                requestAnimationFrame(focusWhenVisible);
            }
        };
        requestAnimationFrame(focusWhenVisible);
    }
}
templates/components/Popover.html.twig
{%- props
    ## string|null Group name shared by mutually exclusive popovers, so only one is open at a time.
    name = null,
    ## boolean Whether the popover is open on initial render.
    open = false
-%}
{%- do provide('popover.open', open) -%}
<div
    data-slot="popover"
    data-state="{{ open ? 'open' : 'closed' }}"
    data-popover-open-value="{{ open ? 'true' : 'false' }}"
    data-popover-name-value="{{ name }}"
    {{ attributes.defaults({
        class: 'group/popover relative inline-block'|tailwind_classes,
        'data-controller': 'popover',
        'data-action': [
            'popover:open@window->popover#handleGroupOpen',
            'click@window->popover#handleOutsideClick',
            'keydown.esc@window->popover#handleEscape',
        ]|join(' ')|html_attr_type('sst'),
    }) }}
>
    {##- A `Popover:Trigger` and a `Popover:Content`. -#}
    {%- block content %}{% endblock -%}
</div>
templates/components/Popover/Content.html.twig
{%- props
    ## 'top'|'right'|'bottom'|'left' Which side of the trigger the content appears on.
    side = 'bottom',
    ## 'start'|'center'|'end' Alignment of the content along the cross axis.
    align = 'center'
-%}
{%- set _popover_open = inject('popover.open', false) -%}
{#- `anchor()` insets rather than `position-area`, which Firefox misplaces in right-to-left: https://bugzil.la/2019601 -#}
{%- set style = html_cva(
    base: 'invisible scale-95 opacity-0 transition-[opacity,scale,visibility] duration-100 ease-out group-data-[state=open]/popover:visible group-data-[state=open]/popover:scale-100 group-data-[state=open]/popover:opacity-100 absolute [&[popover]]:fixed z-50 flex w-72 flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden overflow-visible [&[popover]:not(:popover-open)]:hidden [&[popover]]:inset-auto [&[popover]]:transition-[opacity,scale,visibility,display,overlay] [&[popover]]:transition-discrete starting:open:scale-95 starting:open:opacity-0',
    variants: {
        side: {
            top: 'bottom-full mb-2',
            bottom: 'top-full mt-2',
            left: 'right-full top-1/2 -translate-y-1/2 mr-2 origin-right [&[popover]]:right-[anchor(left)] [&[popover]]:[align-self:anchor-center] [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline] [&[popover]]:translate-none',
            right: 'left-full top-1/2 -translate-y-1/2 ml-2 origin-left [&[popover]]:left-[anchor(right)] [&[popover]]:[align-self:anchor-center] [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline] [&[popover]]:translate-none',
        },
    },
    compound_variants: [
        {side: ['top'], align: ['start'], class: '[&[popover]]:bottom-[anchor(top)] [&[popover]]:start-[anchor(inside)] start-0 ltr:origin-bottom-left rtl:origin-bottom-right [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]'},
        {side: ['top'], align: ['center'], class: '[&[popover]]:bottom-[anchor(top)] [&[popover]]:left-[anchor(center)] [&[popover]]:-translate-x-1/2 [&[popover]]:[position-try-fallbacks:flip-block] start-1/2 -translate-x-1/2 rtl:translate-x-1/2 origin-bottom'},
        {side: ['top'], align: ['end'], class: '[&[popover]]:bottom-[anchor(top)] [&[popover]]:end-[anchor(inside)] end-0 ltr:origin-bottom-right rtl:origin-bottom-left [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]'},
        {side: ['bottom'], align: ['start'], class: '[&[popover]]:top-[anchor(bottom)] [&[popover]]:start-[anchor(inside)] start-0 ltr:origin-top-left rtl:origin-top-right [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]'},
        {side: ['bottom'], align: ['center'], class: '[&[popover]]:top-[anchor(bottom)] [&[popover]]:left-[anchor(center)] [&[popover]]:-translate-x-1/2 [&[popover]]:[position-try-fallbacks:flip-block] start-1/2 -translate-x-1/2 rtl:translate-x-1/2 origin-top'},
        {side: ['bottom'], align: ['end'], class: '[&[popover]]:top-[anchor(bottom)] [&[popover]]:end-[anchor(inside)] end-0 ltr:origin-top-right rtl:origin-top-left [&[popover]]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]'},
    ],
) -%}
<div
    role="dialog"
    data-slot="popover-content"
    data-popover-target="content"
    data-side="{{ side }}"
    data-align="{{ align }}"
    data-state="{{ _popover_open ? 'open' : 'closed' }}"
    aria-hidden="{{ _popover_open ? 'false' : 'true' }}"
    {{ attributes.defaults({
        class: style.apply({side: side, align: align})|tailwind_classes,
    }) }}
>
    {##- The content revealed when the popover is open. -#}
    {%- block content %}{% endblock -%}
</div>
templates/components/Popover/Trigger.html.twig
{%- set _popover_open = inject('popover.open', false) -%}
{%- set popover_trigger_attrs = {
    'data-slot': 'popover-trigger',
    'data-popover-target': 'trigger',
    'data-action': 'click->popover#toggle'|html_attr_type('sst'),
    'aria-haspopup': 'dialog',
    'aria-expanded': _popover_open ? 'true' : 'false',
    'data-state': _popover_open ? 'open' : 'closed',
} -%}
{##- The clickable trigger (e.g., a `Button`) that opens the popover. -#}
{%- block content %}{% endblock -%}

Usage

<twig:Popover name="dimensions" open="false">
    <twig:Popover:Trigger>
        <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>Open popover</twig:Button>
    </twig:Popover:Trigger>
    <twig:Popover:Content side="bottom" align="center">
        Popover content goes here.
    </twig:Popover:Content>
</twig:Popover>

Examples

Basic

100%
Loading...
<div class="flex items-start justify-center pt-6" style="min-height: 260px">
    <twig:Popover>
        <twig:Popover:Trigger>
            <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>Open Popover</twig:Button>
        </twig:Popover:Trigger>
        <twig:Popover:Content align="start">
            <div class="space-y-1">
                <h4 class="text-sm font-medium leading-none">Dimensions</h4>
                <p class="text-xs text-muted-foreground">Set the dimensions for the layer.</p>
            </div>
        </twig:Popover:Content>
    </twig:Popover>
</div>

Alignments

Use the align prop to align the content to the start, center or end of the trigger.

100%
Loading...
<div class="flex items-start justify-center pt-6" style="min-height: 260px">
    <div class="flex gap-6">
        <twig:Popover name="alignments-demo">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" size="sm" {{ ...popover_trigger_attrs }}>Start</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content align="start" class="w-40">
                Aligned to start
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="alignments-demo">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" size="sm" {{ ...popover_trigger_attrs }}>Center</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content align="center" class="w-40">
                Aligned to center
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="alignments-demo">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" size="sm" {{ ...popover_trigger_attrs }}>End</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content align="end" class="w-40">
                Aligned to end
            </twig:Popover:Content>
        </twig:Popover>
    </div>
</div>

With Form

100%
Loading...
<div class="flex items-start justify-center pt-6" style="min-height: 340px">
    <twig:Popover>
        <twig:Popover:Trigger>
            <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>Open Popover</twig:Button>
        </twig:Popover:Trigger>
        <twig:Popover:Content align="start" class="w-64">
            <div class="grid gap-4">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">Dimensions</h4>
                    <p class="text-xs text-muted-foreground">Set the dimensions for the layer.</p>
                </div>
                <div class="grid gap-3">
                    <div class="flex items-center gap-3">
                        <twig:Label for="form-width" class="w-1/2">Width</twig:Label>
                        <input id="form-width" class="h-8 w-full rounded-md border px-2 text-sm" value="100%">
                    </div>
                    <div class="flex items-center gap-3">
                        <twig:Label for="form-height" class="w-1/2">Height</twig:Label>
                        <input id="form-height" class="h-8 w-full rounded-md border px-2 text-sm" value="25px">
                    </div>
                </div>
            </div>
        </twig:Popover:Content>
    </twig:Popover>
</div>

RTL

To enable RTL support, set the dir="rtl" attribute on the root element.

100%
Loading...
<div class="flex flex-col items-center gap-12 py-12" style="min-height: 520px">
    {# Arabic #}
    <div dir="rtl" class="flex flex-wrap justify-center gap-2">
        <twig:Popover name="rtl-ar">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>يسار</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="left">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">الأبعاد</h4>
                    <p class="text-xs text-muted-foreground">تعيين الأبعاد للطبقة.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-ar">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>أعلى</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="top">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">الأبعاد</h4>
                    <p class="text-xs text-muted-foreground">تعيين الأبعاد للطبقة.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-ar">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>أسفل</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="bottom">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">الأبعاد</h4>
                    <p class="text-xs text-muted-foreground">تعيين الأبعاد للطبقة.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-ar">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>يمين</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="right">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">الأبعاد</h4>
                    <p class="text-xs text-muted-foreground">تعيين الأبعاد للطبقة.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
    </div>

    {# Hebrew #}
    <div dir="rtl" class="flex flex-wrap justify-center gap-2">
        <twig:Popover name="rtl-he">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>שמאל</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="left">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">מימדים</h4>
                    <p class="text-xs text-muted-foreground">הגדר את המימדים לשכבה.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-he">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>למעלה</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="top">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">מימדים</h4>
                    <p class="text-xs text-muted-foreground">הגדר את המימדים לשכבה.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-he">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>למטה</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="bottom">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">מימדים</h4>
                    <p class="text-xs text-muted-foreground">הגדר את המימדים לשכבה.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
        <twig:Popover name="rtl-he">
            <twig:Popover:Trigger>
                <twig:Button variant="outline" {{ ...popover_trigger_attrs }}>ימין</twig:Button>
            </twig:Popover:Trigger>
            <twig:Popover:Content side="right">
                <div class="space-y-1">
                    <h4 class="text-sm font-medium leading-none">מימדים</h4>
                    <p class="text-xs text-muted-foreground">הגדר את המימדים לשכבה.</p>
                </div>
            </twig:Popover:Content>
        </twig:Popover>
    </div>
</div>

Accessibility

  • Popover:Content renders role="dialog" and an aria-hidden reflecting the open state. Give it an aria-label, or an aria-labelledby pointing at its heading, since a dialog without a name is announced as an unnamed dialog.
  • Popover:Trigger exposes an aria-expanded that the controller keeps in sync.
  • Opening the popover moves focus into it, to the element carrying autofocus or to the first focusable element. Escape closes it and returns focus to the trigger.
  • In browsers with the Popover API and anchor positioning, the content is shown in the top layer, so an ancestor that hides its overflow does not clip it, and it flips to the other side of the trigger when there is no room. Other browsers show it below or beside the trigger, inside its parent.
  • Unlike Dialog, a popover is not modal: the rest of the page stays reachable and focus is not trapped. Use Dialog when the user must deal with the content before anything else.
  • Use the name prop to group mutually exclusive popovers, so opening one closes the others instead of leaving several unnamed dialogs open at once.

API Reference

<twig:Popover>

Prop Type Default
name 
string|null null
open 
boolean false
Block Description
content A Popover:Trigger and a Popover:Content.

<twig:Popover:Content>

Prop Type Default
side 
'top'|'right'|'bottom'|'left' 'bottom'
align 
'start'|'center'|'end' 'center'
Block Description
content The content revealed when the popover is open.

<twig:Popover:Trigger>

Block Description
content The clickable trigger (e.g., a Button) that opens the popover.