/** * The positioning behind Bootstrap's dropdowns and tooltips in an app built with `bootstrapLite()` * (common/vite/bootstrap-lite.ts), which points `@popperjs/core` here. Popper rides the first download of every page * that can open a dropdown (20 KB, 6.6 KB at brotli 11) for the one call Bootstrap makes: * `createPopper(reference, popper, { placement, modifiers })`, then `update()` and `destroy()`. This puts the popper in * the box Popper 2.11 puts it for what Bootstrap passes — `offset`, `flip` (with or without `fallbackPlacements`), * `preventOverflow` (tethered, against the viewport and the clipping ancestors), `arrow`, and `applyStyles` switched off * for a static dropdown — in a fraction of the code: * - coordinates count from the popper's offset parent (the page for a static ), as Popper's do; * - flip takes the first placement that fits on its own side and both cross sides, then on its own side and the one * it aligns to, then on its own side; else the first one; * - the cross-axis shift keeps the popper inside, but never further from its reference than the arrow's length; * - the arrow points at the reference's centre, inside the popper; offsets are rounded to the device pixel, and * `data-popper-placement` names the final placement (Bootstrap's CSS styles the tooltip arrow by it). * Not here, as Bootstrap asks for none of it: strategies other than `absolute`, modifier options beyond those above, * custom modifiers (Bootstrap's one pre-sets `data-popper-placement`, which this sets itself before it measures the * arrow), offset parents a `scale()` shrinks. The popper is placed by `top` / `left: 0` and a `transform`, where Popper * anchors a top or left one by its far edge: the same box, but for the device pixel each rounds to. * `dev/validate-popper-lite.mjs` checks the boxes against Popper's in Chromium. */ interface Box { left: number; top: number; right: number; bottom: number } interface PopperModifier { name: string; enabled?: boolean; options?: Record } interface VirtualElement { getBoundingClientRect: () => DOMRect } const OPPOSITE: Record = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }; const STYLES = [ 'position', 'top', 'right', 'bottom', 'left', 'margin', 'transform', ]; const opposite = (placement: string): string => placement.replace(/^\w+/, side => OPPOSITE[side] ?? side); const oppositeVariation = (placement: string): string => placement.replace(/start|end/, v => (v === 'start' ? 'end' : 'start')); const clamp = ( value: number, min: number, max: number, ): number => Math.max(min, Math.min(value, max)); const isScrollParent = (element: Element): boolean => { const { overflow, overflowX, overflowY } = getComputedStyle(element); return /auto|scroll|overlay|hidden/.test(overflow + overflowX + overflowY); }; /** The layout size, fractional unless a transform scales it (Popper's `getLayoutRect`). */ const sizeOf = (element: HTMLElement): { width: number; height: number } => { const rect = element.getBoundingClientRect(); return { width: Math.abs(rect.width - element.offsetWidth) <= 1 ? rect.width : element.offsetWidth, height: Math.abs(rect.height - element.offsetHeight) <= 1 ? rect.height : element.offsetHeight, }; }; /** The element the popper's `top` / `left` count from, or null for the page (Popper's `getOffsetParent`). */ const offsetParentOf = (popper: HTMLElement): HTMLElement | null => { let parent = popper.offsetParent as HTMLElement | null; // A static table cell is no containing block, though it is an offset parent. while (parent != null && /^(?:table|td|th)$/i.test(parent.nodeName) && getComputedStyle(parent).position === 'static') { parent = parent.offsetParent as HTMLElement | null; } return parent == null || parent === document.documentElement || (parent === document.body && getComputedStyle(parent).position === 'static') ? null : parent; }; /** The visible area the popper keeps inside: the viewport, cut by every clipping ancestor of its offset parent. */ const boundsOf = (offsetParent: HTMLElement | null): Box => { const html = document.documentElement; const visual = window.visualViewport; // Safari measures boxes in its visual viewport already; the others in the layout one, where it is offset. const shifted = visual != null && !/^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent); const left = shifted ? visual.offsetLeft : 0; const top = shifted ? visual.offsetTop : 0; const bounds = { left, top, right: left + (visual?.width ?? html.clientWidth), bottom: top + (visual?.height ?? html.clientHeight) }; for (let element: Element | null = offsetParent; element != null && element !== document.body && element !== html; element = element.parentElement) { if (isScrollParent(element)) { const rect = element.getBoundingClientRect(); bounds.left = Math.max(bounds.left, rect.left + element.clientLeft); bounds.top = Math.max(bounds.top, rect.top + element.clientTop); bounds.right = Math.min(bounds.right, rect.left + element.clientLeft + element.clientWidth); bounds.bottom = Math.min(bounds.bottom, rect.top + element.clientTop + element.clientHeight); } } return bounds; }; /** Popper's entry point, as Bootstrap calls it (`import * as Popper from '@popperjs/core'`). */ export const createPopper = ( reference: Element | VirtualElement, popper: HTMLElement, options: { placement?: string; modifiers?: PopperModifier[] } = {}, ) => { const modifiers: Record = {}; for (const modifier of options.modifiers ?? []) { modifiers[modifier.name] = { ...modifiers[modifier.name], ...modifier, options: { ...modifiers[modifier.name]?.options, ...modifier.options } }; } const enabled = (name: string): boolean => modifiers[name]?.enabled !== false; const optionsOf = (name: string): Record => modifiers[name]?.options ?? {}; const arrowOption = optionsOf('arrow').element ?? '[data-popper-arrow]'; const arrow: HTMLElement | null = enabled('arrow') ? (typeof arrowOption === 'string' ? popper.querySelector(arrowOption) : arrowOption) : null; const writes = enabled('applyStyles'); const state = { placement: options.placement ?? 'bottom', elements: { reference, popper, arrow } }; let pending: Promise | null = null; let destroyed = false; const forceUpdate = (): void => { if (destroyed) { return; } const ref = reference.getBoundingClientRect(); const { width, height } = sizeOf(popper); const offsetParent = offsetParentOf(popper); const bounds = boundsOf(offsetParent); const offset = optionsOf('offset').offset ?? [ 0, 0, ]; // The popper's box at `placement`, offset applied. const place = (placement: string): Box => { const [ side, variation, ] = placement.split('-'); const [ skidding = 0, distance = 0, ] = typeof offset === 'function' ? offset({ reference: ref, popper: { width, height }, placement }) : offset; let left = side === 'left' ? ref.left - width - distance : side === 'right' ? ref.right + distance : ref.left + (ref.width - width) / 2; let top = side === 'top' ? ref.top - height - distance : side === 'bottom' ? ref.bottom + distance : ref.top + (ref.height - height) / 2; if (side === 'top' || side === 'bottom') { left = (variation === 'start' ? ref.left : variation === 'end' ? ref.right - width : left) + skidding; } else { top = (variation === 'start' ? ref.top : variation === 'end' ? ref.bottom - height : top) + skidding; } return { left, top, right: left + width, bottom: top + height }; }; // How far the box reaches past the bounds on `side` (positive = past). const past = (box: Box, side: string): number => (side === 'top' || side === 'left' ? bounds[side] - box[side] : box[side] - bounds[side]); // Popper's flip checks: its own side, the cross side the variation aligns to, the other cross side. const checks = (placement: string): boolean[] => { const [ side, variation, ] = placement.split('-'); const vertical = side === 'top' || side === 'bottom'; const box = place(placement); let near = vertical ? (variation === 'start' ? 'right' : 'left') : (variation === 'start' ? 'bottom' : 'top'); if (vertical ? ref.width > width : ref.height > height) { near = OPPOSITE[near]; } return [ past(box, side) <= 0, past(box, near) <= 0, past(box, OPPOSITE[near]) <= 0, ]; }; // `auto`: the four sides, least overflowing first. const expand = (placement: string): string[] => (placement.startsWith('auto') ? Object.keys(OPPOSITE).sort((a, b) => past(place(a), a) - past(place(b), b)) : [placement]); const asked = options.placement ?? 'bottom'; const candidates = (enabled('flip') ? [ asked, ...(optionsOf('flip').fallbackPlacements ?? (asked.includes('-') ? [ oppositeVariation(asked), opposite(asked), oppositeVariation(opposite(asked)), ] : [opposite(asked)])), ] : [asked]).flatMap(expand); const results = candidates.map(checks); const pick = (count: number): string | undefined => candidates.find((_, index) => results[index].slice(0, count).every(Boolean)); const placement = pick(3) ?? pick(2) ?? pick(1) ?? candidates[0]; const vertical = placement.startsWith('top') || placement.startsWith('bottom'); const box = place(placement); state.placement = placement; if (writes) { // Before the arrow is measured: Bootstrap's CSS sizes it by this attribute. popper.setAttribute('data-popper-placement', placement); } const arrowLength = arrow == null ? 0 : sizeOf(arrow)[vertical ? 'width' : 'height']; if (enabled('preventOverflow')) { // Inside the bounds, but never further from the reference than the arrow's length (Popper's tether). const tether = Math.min(arrowLength, vertical ? ref.width : ref.height); if (vertical) { box.left = clamp( box.left, Math.min(bounds.left, ref.right - tether), Math.max(bounds.right - width, ref.left + tether - width), ); } else { box.top = clamp( box.top, Math.min(bounds.top, ref.bottom - tether), Math.max(bounds.bottom - height, ref.top + tether - height), ); } } if (!writes) { return; } const dpr = window.devicePixelRatio || 1; const round = (value: number): number => Math.round(value * dpr) / dpr || 0; const origin = offsetParent?.getBoundingClientRect(); const x = box.left - (origin == null ? -window.scrollX : origin.left + offsetParent.clientLeft - offsetParent.scrollLeft); const y = box.top - (origin == null ? -window.scrollY : origin.top + offsetParent.clientTop - offsetParent.scrollTop); Object.assign(popper.style, { position: 'absolute', top: '0', right: 'auto', bottom: 'auto', left: '0', margin: '0', transform: `translate(${round(x)}px, ${round(y)}px)` }); if (arrow != null) { const center = vertical ? ref.left + ref.width / 2 - box.left : ref.top + ref.height / 2 - box.top; const shift = round(clamp( center - arrowLength / 2, 0, (vertical ? popper.clientWidth : popper.clientHeight) - arrowLength, )); Object.assign(arrow.style, { position: 'absolute', top: vertical ? '' : '0', left: vertical ? '0' : '', transform: vertical ? `translate(${shift}px, 0px)` : `translate(0px, ${shift}px)` }); } }; // At most once per tick, on a microtask, as Popper's: Bootstrap shows the menu right after creating it. const update = () => { pending ??= Promise.resolve().then(() => { pending = null; forceUpdate(); return state; }); return pending; }; const listen = (method: 'addEventListener' | 'removeEventListener'): void => { window[method]( 'scroll', update, { capture: true, passive: true } as AddEventListenerOptions, ); window[method]( 'resize', update, { passive: true } as AddEventListenerOptions, ); window.visualViewport?.[method]( 'scroll', update, { passive: true } as AddEventListenerOptions, ); }; if (writes) { // Popper's start styles, so the first measurement sees the box it will place: the arrow too, which Bootstrap's CSS // leaves in the flow — the tooltip its height taller. Object.assign(popper.style, { position: 'absolute', top: '0', left: '0', margin: '0' }); arrow?.style.setProperty('position', 'absolute'); } listen('addEventListener'); update(); return { state, update, forceUpdate, destroy: () => { if (!destroyed) { destroyed = true; listen('removeEventListener'); if (writes) { STYLES.forEach(property => popper.style.removeProperty(property)); popper.removeAttribute('data-popper-placement'); [ 'position', 'top', 'left', 'transform', ].forEach(property => arrow?.style.removeProperty(property)); } } }, }; };