All files / positioning positioning.ts

98.55% Statements 68/69
97.29% Branches 72/74
100% Functions 10/10
98.27% Lines 57/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183                                                                                                                                                5x 47x 47x           47x                 59x 59x 59x   59x   59x 59x 106x   106x 106x 106x 106x 106x 106x 106x 106x 103x 103x   3x 3x   106x   59x 98x       59x 59x 59x 59x 47x 47x 47x 1x 1x 1x     59x 59x 52x         59x                           50x 50x 50x 50x 50x     50x 50x 50x 1x 1x 1x   50x 50x 50x     50x         2x   1x      
import { getScrollableAncestors, listen } from '../dom/dom';
import type { Unsubscribe } from '../core/types';
 
/** Logical side and alignment for an anchored floating element. @public */
export type Placement =
  | 'top-start'
  | 'top'
  | 'top-end'
  | 'right-start'
  | 'right'
  | 'right-end'
  | 'bottom-start'
  | 'bottom'
  | 'bottom-end'
  | 'left-start'
  | 'left'
  | 'left-end';
 
/** Minimal rectangle implemented by DOM elements and virtual pointer anchors. @public */
export interface AnchorRect {
  /** Horizontal viewport coordinate. */
  readonly x: number;
  /** Vertical viewport coordinate. */
  readonly y: number;
  /** Anchor width. */
  readonly width: number;
  /** Anchor height. */
  readonly height: number;
}
 
/** Consumer-provided virtual anchor, typically created from pointer coordinates. @public */
export interface VirtualAnchor {
  /** Returns a fresh viewport-relative rectangle. */
  getBoundingClientRect(): AnchorRect;
  /** Optional real element used to resolve document, direction, and scroll ancestors. */
  readonly contextElement?: Element;
}
 
/** Collision and geometry settings shared by anchored components. @public */
export interface FloatingPositionOptions {
  /** Preferred side and alignment. @defaultValue `bottom-start` */
  readonly placement?: Placement;
  /** Gap between anchor and floating element in CSS pixels. @defaultValue `4` */
  readonly offset?: number;
  /** Viewport collision padding in CSS pixels. @defaultValue `8` */
  readonly collisionPadding?: number;
  /** Allows opposite-side fallback when the preferred side overflows. @defaultValue `true` */
  readonly flip?: boolean;
  /** Clamps cross-axis coordinates inside the viewport. @defaultValue `true` */
  readonly shift?: boolean;
  /** Resolves logical start/end alignment for RTL content. @defaultValue `false` */
  readonly rtl?: boolean;
  /** Explicit viewport width for deterministic or virtualized calculations. */
  readonly viewportWidth?: number;
  /** Explicit viewport height for deterministic or virtualized calculations. */
  readonly viewportHeight?: number;
}
 
/** Coordinates and collision metadata returned without applying visual styles. @public */
export interface PositionResult {
  /** Horizontal viewport coordinate. */
  readonly x: number;
  /** Vertical viewport coordinate. */
  readonly y: number;
  /** Final placement after collision handling. */
  readonly placement: Placement;
  /** Whether collision handling changed the preferred side. */
  readonly flipped: boolean;
  /** Whether collision handling shifted either coordinate. */
  readonly shifted: boolean;
}
 
const opposite = (placement: Placement): Placement => {
  const [side, alignment] = placement.split('-') as [string, string | undefined];
  const sides: Record<string, string> = {
    top: 'bottom',
    bottom: 'top',
    left: 'right',
    right: 'left',
  };
  return `${sides[side]}${alignment ? `-${alignment}` : ''}` as Placement;
};
 
/** Calculates anchored coordinates with flip, shift, and RTL support. @public */
export function calculatePosition(
  anchor: AnchorRect,
  floating: Readonly<{ width: number; height: number }>,
  options: FloatingPositionOptions = {},
): PositionResult {
  const preferred = options.placement ?? 'bottom-start';
  const gap = options.offset ?? 4;
  const padding = options.collisionPadding ?? 8;
  const viewportWidth =
    options.viewportWidth ?? (typeof window === 'undefined' ? 1024 : window.innerWidth);
  const viewportHeight =
    options.viewportHeight ?? (typeof window === 'undefined' ? 768 : window.innerHeight);
  const coordinates = (placement: Placement): { x: number; y: number } => {
    const [side, rawAlignment] = placement.split('-') as [string, 'start' | 'end' | undefined];
    const alignment =
      options.rtl && rawAlignment ? (rawAlignment === 'start' ? 'end' : 'start') : rawAlignment;
    let x = anchor.x + (anchor.width - floating.width) / 2;
    let y = anchor.y + (anchor.height - floating.height) / 2;
    if (side === 'top') y = anchor.y - floating.height - gap;
    if (side === 'bottom') y = anchor.y + anchor.height + gap;
    if (side === 'left') x = anchor.x - floating.width - gap;
    if (side === 'right') x = anchor.x + anchor.width + gap;
    if (side === 'top' || side === 'bottom') {
      if (alignment === 'start') x = anchor.x;
      if (alignment === 'end') x = anchor.x + anchor.width - floating.width;
    } else {
      if (alignment === 'start') y = anchor.y;
      if (alignment === 'end') y = anchor.y + anchor.height - floating.height;
    }
    return { x, y };
  };
  const overflows = ({ x, y }: { x: number; y: number }): boolean =>
    x < padding ||
    y < padding ||
    x + floating.width > viewportWidth - padding ||
    y + floating.height > viewportHeight - padding;
  let placement = preferred;
  let point = coordinates(placement);
  let flipped = false;
  if ((options.flip ?? true) && overflows(point)) {
    const candidate = opposite(placement);
    const candidatePoint = coordinates(candidate);
    if (!overflows(candidatePoint)) {
      placement = candidate;
      point = candidatePoint;
      flipped = true;
    }
  }
  const unclamped = point;
  if (options.shift ?? true) {
    point = {
      x: Math.min(Math.max(point.x, padding), viewportWidth - floating.width - padding),
      y: Math.min(Math.max(point.y, padding), viewportHeight - floating.height - padding),
    };
  }
  return Object.freeze({
    ...point,
    placement,
    flipped,
    shifted: point.x !== unclamped.x || point.y !== unclamped.y,
  });
}
 
/** Recalculates position on relevant scroll, resize, and element resize changes. @public */
export function autoUpdatePosition(
  anchor: Element | VirtualAnchor,
  floating: Element,
  update: () => void,
): Unsubscribe {
  const context = 'ownerDocument' in anchor ? anchor : anchor.contextElement;
  const ownerWindow = floating.ownerDocument.defaultView;
  const cleanups: Unsubscribe[] = [];
  if (ownerWindow) cleanups.push(listen(ownerWindow, 'resize', update));
  for (const ancestor of context ? getScrollableAncestors(context) : []) {
    cleanups.push(listen(ancestor, 'scroll', update, { passive: true }));
  }
  const ResizeObserverConstructor = ownerWindow?.ResizeObserver;
  const observer = ResizeObserverConstructor ? new ResizeObserverConstructor(update) : undefined;
  if (observer) {
    Eif (context) observer.observe(context);
    observer.observe(floating);
    cleanups.push(() => observer.disconnect());
  }
  update();
  return () =>
    cleanups
      .splice(0)
      .reverse()
      .forEach((cleanup) => cleanup());
}
 
/** Creates a point-sized virtual anchor for context menus and pointer popovers. @public */
export function createVirtualAnchor(x: number, y: number, contextElement?: Element): VirtualAnchor {
  return {
    ...(contextElement ? { contextElement } : {}),
    getBoundingClientRect: () => ({ x, y, width: 0, height: 0 }),
  };
}