Skip to content

Popover

Rich content in a panel anchored to a trigger.

View as Markdown

Example

Installation

npx fizzy-ui add popover

Copies popover.ts into src/app/ui/ and installs what it needs. Run init once first.

Keyboard

KeyAction
Enter / SpaceOpen from the trigger; focus moves inside
EscapeClose and return focus
Tab outClose

Accessibility

No axe-core violations axe-core 4.14.0 checks this example, closed and with its panels open, on every build; the site is not published otherwise.

  • The panel is a non-modal dialog: give it an aria-label.

Testing

FzPopoverHarness drives it in your tests, the way a user would, with the Angular CDK harness API. --harness also copies popover.harness.ts; its methods are documented in the file.

npx fizzy-ui add popover --harness
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { FzPopoverHarness } from './ui/popover.harness';

const popover = await TestbedHarnessEnvironment.loader(fixture).getHarness(FzPopoverHarness);

Source

The exact file add copies. It is yours to edit.

popover.ts
import { DestroyRef, Directive, ElementRef, Injector, afterNextRender, effect, inject, input, model, untracked } from '@angular/core';
import { DomPortal } from '@angular/cdk/portal';
import {
  ConnectedPosition,
  OverlayRef,
  createFlexibleConnectedPositionStrategy,
  createOverlayRef,
  createRepositionScrollStrategy,
} from '@angular/cdk/overlay';

const POSITIONS: ConnectedPosition[] = [
  { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', offsetY: 4 },
  { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', offsetY: -4 },
];
const FOCUSABLE = 'input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),[href],[tabindex]:not([tabindex="-1"])';
let nextId = 0;

/**
 * Exit animation: marks `el` data-closing (its exit keyframes) and inert, then calls `done` once the
 * animations end. With none (motion off, or tests) it calls `done` at once and returns undefined;
 * otherwise it returns a cancel, for a reopen.
 */
function leave(el: HTMLElement, done: () => void): (() => void) | undefined {
  let live = true;
  const clear = () => {
    el.removeAttribute('data-closing');
    el.inert = false;
  };
  el.setAttribute('data-closing', '');
  el.inert = true;
  const running = el.getAnimations?.() ?? [];
  if (!running.length) {
    done();
    clear();
    return undefined;
  }
  void Promise.allSettled(running.map((a) => a.finished)).then(() => {
    if (!live) return;
    live = false;
    done();
    clear();
  });
  return () => {
    live = false;
    clear();
  };
}

/**
 * Non-modal popup: `<button fzButton [fzPopoverTrigger]="pop">` + `<div fzPopover #pop="fzPopover" aria-label="…">`.
 * Opening moves focus inside (first focusable, else the panel); Escape closes and gives focus back
 * to the trigger; a click outside or focus leaving closes it. `[(open)]` works too.
 */
@Directive({
  selector: '[fzPopover]',
  exportAs: 'fzPopover',
  host: {
    role: 'dialog',
    tabindex: '-1',
    '[id]': 'id()',
    '[attr.data-open]': 'open()',
    '(keydown.escape)': 'close()',
    '(focusout)': 'onFocusOut($event)',
    '(document:pointerdown)': 'onOutside($event)',
    class:
      'w-72 rounded-md border bg-background p-4 text-sm text-foreground shadow-md outline-none animate-fz-popup ' +
      // hidden yields to data-closing, so the user's own display (flex, grid) stays during the fade
      'data-[open=false]:not-data-closing:hidden data-closing:animate-fz-fade-out',
  },
})
export class FzPopover {
  readonly open = model(false);
  readonly id = input(`fz-popover-${nextId++}`);
  /** Set by `fzPopoverTrigger`: what the panel is placed against and gives focus back to. */
  anchor?: HTMLElement;
  private readonly el: HTMLElement = inject(ElementRef).nativeElement;
  private readonly injector = inject(Injector);
  private overlay?: OverlayRef;
  private leaving?: () => void;

  constructor() {
    effect(() => {
      const open = this.open();
      untracked(() => {
        if (open) this.attach();
        else if (this.overlay?.hasAttached())
          this.leaving ??= leave(this.el, () => {
            this.leaving = undefined;
            this.overlay?.detach();
          });
      });
    });
    inject(DestroyRef).onDestroy(() => this.overlay?.dispose());
  }

  toggle() {
    this.open.update((o) => !o);
  }

  close(restoreFocus = true) {
    if (!this.open()) return;
    this.open.set(false);
    if (restoreFocus) this.anchor?.focus();
  }

  private attach() {
    this.leaving?.(); // reopened while closing
    this.leaving = undefined;
    if (!this.anchor) return;
    this.overlay ??= createOverlayRef(this.injector, {
      usePopover: true,
      positionStrategy: createFlexibleConnectedPositionStrategy(this.injector, this.anchor)
        .withPopoverLocation('inline')
        .withTransformOriginOn(':scope > .cdk-overlay-pane > *')
        .withPositions(POSITIONS),
      scrollStrategy: createRepositionScrollStrategy(this.injector),
    });
    if (!this.overlay.hasAttached()) this.overlay.attach(new DomPortal(this.el));
    afterNextRender(() => (this.el.querySelector<HTMLElement>(FOCUSABLE) ?? this.el).focus(), { injector: this.injector });
  }

  private inside(node: EventTarget | null) {
    return node instanceof Node && (this.el.contains(node) || !!this.anchor?.contains(node));
  }

  protected onOutside(event: PointerEvent) {
    if (this.open() && !this.inside(event.target)) this.close(false);
  }

  // Tab out of the panel closes it. null means focus went nowhere in particular (e.g. a click on text).
  protected onFocusOut(event: FocusEvent) {
    if (event.relatedTarget && !this.inside(event.relatedTarget)) this.close(false);
  }
}

@Directive({
  selector: '[fzPopoverTrigger]',
  host: {
    'data-popover-trigger': '', // the binding leaves no attribute; tests (FzPopoverHarness) find it by this
    'aria-haspopup': 'dialog',
    '[attr.aria-expanded]': 'fzPopoverTrigger().open()',
    '[attr.aria-controls]': 'fzPopoverTrigger().id()',
    '(click)': 'fzPopoverTrigger().toggle()',
  },
})
export class FzPopoverTrigger {
  readonly fzPopoverTrigger = input.required<FzPopover>();

  constructor() {
    const el: HTMLElement = inject(ElementRef).nativeElement;
    effect(() => (this.fzPopoverTrigger().anchor = el));
  }
}

export const FZ_POPOVER = [FzPopover, FzPopoverTrigger] as const;