All files / common/helpers positioning.helpers.ts

7.84% Statements 12/153
0% Branches 0/130
0% Functions 0/17
7.84% Lines 12/153

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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446                        1x                 1x                 1x                 1x                                     1x                                                   1x                                                     1x                                                 1x                                                                         1x                                                                                     1x                                             1x                                       1x                                                                                                                                                                                                                                                                                                                                                                                    
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { isRTL } from './rtl';
 
export type Direction = 'down' | 'up' | 'start' | 'end';
export type PlacementBasicVertical = 'top' | 'bottom';
export type PlacementBasic = 'start' | 'end' | PlacementBasicVertical;
export type Placement = '' | PlacementBasic | `${PlacementBasic} ${PlacementBasic}`;
export type Align = 'start' | 'center' | 'end';
 
export const AXIS_X = {
  axis: 'X',
  directionRegular: 'end',
  directionReverse: 'start',
  upperBound: 'left',
  lowerBound: 'right',
  size: 'width',
  windowSize: 'innerWidth'
} as const;
export const AXIS_Y = {
  axis: 'Y',
  directionRegular: 'down',
  directionReverse: 'up',
  upperBound: 'top',
  lowerBound: 'bottom',
  size: 'height',
  windowSize: 'innerHeight'
} as const;
export const BOUNDING_RECT_WINDOW = {
  getBoundingClientRect: () => ({
    top: 0,
    left: 0,
    bottom: window.innerHeight,
    right: window.innerWidth
  })
};
 
export const resolveReference = (
  hostElement: HTMLElement,
  reference: string
): HTMLElement | null => {
  Iif (reference) {
    const childReferenceCheck = hostElement.querySelector(reference);
    Iif (childReferenceCheck) {
      return childReferenceCheck as HTMLElement;
    }
    const referenceCheck = hostElement.closest(reference);
    Iif (referenceCheck) {
      return referenceCheck as HTMLElement;
    }
    const all = document.querySelectorAll(reference);
    return (all[all.length - 1] as HTMLElement) ?? null;
  }
  return null;
};
 
const getScrollParentsChain = (
  element: HTMLElement | null,
  axis: 'X' | 'Y',
  scrollParentsList: (typeof BOUNDING_RECT_WINDOW)[] = []
): (typeof BOUNDING_RECT_WINDOW)[] => {
  Iif (element) {
    const overflowStyle =
      getComputedStyle(element)[axis === 'X' ? 'overflowX' : 'overflowY'] || 'visible';
    Iif (
      element[axis === 'X' ? 'clientWidth' : 'clientHeight'] &&
      overflowStyle !== 'visible' &&
      overflowStyle !== 'hidden'
    ) {
      scrollParentsList.push(document.documentElement === element ? BOUNDING_RECT_WINDOW : element);
    }
    Iif (element !== document.documentElement) {
      getScrollParentsChain(
        (element as any).dropdownParentElement ?? element.parentElement ?? document.body,
        axis,
        scrollParentsList
      );
    }
  }
  return scrollParentsList;
};
 
const getCombinedBoundingClientRect = (
  elements: HTMLElement[]
): { top: number; bottom: number; left: number; right: number } => {
  let top = 0;
  let bottom = 0;
  let left = 0;
  let right = 0;
  Iif (elements.length > 0) {
    const tops: number[] = [];
    const bottoms: number[] = [];
    const lefts: number[] = [];
    const rights: number[] = [];
    elements.forEach(element => {
      const rect = element.getBoundingClientRect();
      tops.push(rect.top);
      bottoms.push(rect.bottom);
      lefts.push(rect.left);
      rights.push(rect.right);
    });
    top = Math.min(...tops);
    bottom = Math.max(...bottoms);
    left = Math.min(...lefts);
    right = Math.max(...rights);
  }
  return { top, bottom, left, right };
};
 
const calculatePlacementRefOuterBounds = (
  currentAxis: typeof AXIS_X | typeof AXIS_Y,
  placementReferenceElement: HTMLElement | null
): { upper: number; lower: number } => {
  // The chain of scroll parents of the placement ref element up to and often including the body, checking for possible overlaps.
  const placementRefScrollParents = getScrollParentsChain(
    placementReferenceElement,
    currentAxis.axis
  );
  const placementRefScrollParentRects = placementRefScrollParents.map(item =>
    item.getBoundingClientRect()
  );
  // The biggest upper bound (top, left) of all scroll parents (and viewport = 0), the point before which content will be cut off.
  const placementRefScrollParentsUpperBound = Math.max(
    0,
    ...placementRefScrollParentRects.map(item => item[currentAxis.upperBound])
  );
  // The smallest lower bound (bottom, right) of all scroll parents (and viewport), the point after which content will be cut off.
  const placementRefScrollParentsLowerBound = Math.min(
    window[currentAxis.windowSize],
    ...placementRefScrollParentRects.map(item => item[currentAxis.lowerBound])
  );
  return { upper: placementRefScrollParentsUpperBound, lower: placementRefScrollParentsLowerBound };
};
 
const calculateDirectionFromPlacementRef = (params: {
  currentAxis: typeof AXIS_X | typeof AXIS_Y;
  positionRegular: { left: number; top: number };
  positionReverse: { left: number; top: number };
  contentSize: number;
  placementRefBounds: { upper: number; lower: number };
  currentDirection: Direction;
  rtl?: boolean;
}): Direction => {
  const {
    currentAxis,
    positionRegular,
    positionReverse,
    contentSize,
    placementRefBounds,
    currentDirection,
    rtl
  } = params;
  // A number showing how many visible pixels would be available from the placement ref in regular / scroll (down, end) direction
  const placementRefSpaceRegular =
    placementRefBounds.lower - positionRegular[currentAxis.upperBound];
  // A number showing how many visible pixels would be available from the placement ref in reverse (up, start) direction
  const placementRefSpaceReverse =
    positionReverse[currentAxis.upperBound] - placementRefBounds.upper;
  if (placementRefSpaceReverse < contentSize && placementRefSpaceRegular < contentSize) {
    // If there would not be enough room in both directions, always prefer regular / scroll (down, end) direction,
    // since this way the element can expand and scroll while this cannot happen if there's not enough room in front.
    return rtl ? currentAxis.directionReverse : currentAxis.directionRegular;
  } else if (placementRefSpaceReverse < contentSize) {
    return currentAxis.directionRegular;
  } else Iif (placementRefSpaceRegular < contentSize) {
    return currentAxis.directionReverse;
  }
  // If there would be enough room in both directions, use the set direction (or the regular one if not set).
  return currentDirection;
};
 
const getAbsoluteContentPosition = (params: {
  direction: Direction;
  placement: Placement;
  element: HTMLElement;
  align: Align;
  rtl?: boolean;
}): { left: number; top: number } => {
  const { direction, placement, element, align, rtl } = params;
  const elementRect = element.getBoundingClientRect();
 
  const start = rtl ? elementRect.right : elementRect.left;
  const end = rtl ? elementRect.left : elementRect.right;
 
  let relativeLeftOffset = 0;
  if (direction === 'start' || direction === 'end') {
    relativeLeftOffset =
      placement.includes('end') || (!placement.includes('start') && direction === 'end')
        ? end
        : start;
  } else {
    if (placement.includes('start')) {
      relativeLeftOffset = start;
    } else {
      if (placement.includes('end') || align === 'end') {
        relativeLeftOffset = end;
      } else if (align === 'center') {
        relativeLeftOffset = elementRect.left + (elementRect.right - elementRect.left) / 2;
      } else {
        relativeLeftOffset = start;
      }
    }
  }
  let relativeTopOffset = 0;
  if (direction === 'up') {
    relativeTopOffset = placement.includes('bottom') ? elementRect.bottom : elementRect.top;
  } else if (direction === 'start' || direction === 'end') {
    relativeTopOffset = !placement.includes('bottom') ? elementRect.top : elementRect.bottom;
  } else {
    relativeTopOffset = placement.includes('top') ? elementRect.top : elementRect.bottom;
  }
  return { left: relativeLeftOffset, top: relativeTopOffset };
};
 
const getRelativeContentPosition = (params: {
  contentElement: HTMLElement;
  direction: Direction;
  placement: Placement;
  placementReferenceElement: HTMLElement;
  align: Align;
  rtl?: boolean;
}): { left: number; top: number } => {
  const { contentElement, direction, placement, placementReferenceElement, align, rtl } = params;
  const contentParent = (contentElement as HTMLElement).offsetParent ?? document.body;
  const contentParentRect = contentParent.getBoundingClientRect();
  const relativePosition = getAbsoluteContentPosition({
    direction,
    placement,
    element: placementReferenceElement,
    align,
    rtl
  });
  const leftOffset = relativePosition.left - contentParentRect.left + contentParent.scrollLeft;
  const topOffset = relativePosition.top - contentParentRect.top + contentParent.scrollTop;
  return { left: leftOffset, top: topOffset };
};
 
export const getContentPositionString = (params: {
  contentElement: HTMLElement;
  direction: Direction;
  placement: Placement;
  placementReferenceElement: HTMLElement;
  align: Align;
  rtl?: boolean;
}): string => {
  const { contentElement, direction, placement, placementReferenceElement, align, rtl } = params;
  const position = getRelativeContentPosition({
    contentElement,
    direction,
    placement,
    placementReferenceElement,
    align,
    rtl: rtl ?? isRTL()
  });
  return `translate3d(${position.left}px, ${position.top}px, 0px)`;
};
 
export const responsivelyCheckDirection = (params: {
  isScrolling?: boolean;
  currentDirection: Direction;
  contentElements: HTMLElement[];
  hostElement: HTMLElement | null;
  placement: Placement;
  placementReferenceElement: HTMLElement;
  align: Align;
  responsiveDirectionToPlacement: boolean;
  closeOnPlacementReferenceScrollOut: boolean;
  closeOnContentScrollOut: boolean;
  minSpaceThresholdFactor?: number;
  placementReverse?: Placement;
  rtl?: boolean;
}): { responsiveDirection?: Direction; close: boolean } => {
  const {
    isScrolling,
    currentDirection,
    contentElements,
    hostElement,
    placement,
    placementReferenceElement,
    align,
    responsiveDirectionToPlacement,
    closeOnPlacementReferenceScrollOut,
    closeOnContentScrollOut,
    minSpaceThresholdFactor,
    placementReverse,
    rtl
  } = params;
 
  const actualRtl = rtl ?? isRTL();
 
  let responsiveDirection: Direction | undefined;
 
  const actualCurrentDirection = actualRtl
    ? currentDirection === 'start'
      ? 'end'
      : currentDirection === 'end'
        ? 'start'
        : currentDirection
    : currentDirection;
 
  // Defines how the properties to access are named in the current axis.
  const currentAxis = currentDirection === 'start' || currentDirection === 'end' ? AXIS_X : AXIS_Y;
  // The combined (enclosing) client rect for all component contents.
  const contentsRect = getCombinedBoundingClientRect(contentElements);
  // The chain of scroll parents of the container host element up to and often including the body, checking for possible overlaps.
  const containerScrollParents = getScrollParentsChain(hostElement, currentAxis.axis);
  const containerScrollParentRects = containerScrollParents.map(item =>
    item.getBoundingClientRect()
  );
  // The biggest upper bound (top, left) of all scroll parents (and viewport = 0), the point before which content will be cut off.
  const scrollParentsUpperBound = Math.max(
    0,
    ...containerScrollParentRects.map(item => item[currentAxis.upperBound])
  );
  // The smallest lower bound (bottom, right) of all scroll parents (and viewport), the point after which content will be cut off.
  const scrollParentsLowerBound = Math.min(
    window[currentAxis.windowSize],
    ...containerScrollParentRects.map(item => item[currentAxis.lowerBound])
  );
 
  // The point from which the component will be opened if opening in regular / scroll (down, end) direction.
  // Influenced by `componentPlacementReference`, `componentPlacement` and `componentAlign`.
  const positionRegular = getAbsoluteContentPosition({
    direction: currentAxis.directionRegular,
    placement,
    element: placementReferenceElement,
    align
  });
  // The point from which the component will be opened if opening in reverse (up, start) direction.
  // Influenced by `componentPlacementReference`, `componentPlacement` and `componentAlign`.
  const positionReverse = getAbsoluteContentPosition({
    direction: currentAxis.directionReverse,
    placement: placementReverse ?? placement,
    element: placementReferenceElement,
    align
  });
 
  // The enclosing size (height, width) of all contents combined
  const contentsSize = contentsRect[currentAxis.lowerBound] - contentsRect[currentAxis.upperBound];
 
  // A number showing how many visible pixels would be available in regular / scroll (down, end) direction
  const spaceRegular = scrollParentsLowerBound - positionRegular[currentAxis.upperBound];
  // A number showing how many visible pixels would be available in reverse (up, start) direction
  const spaceReverse = positionReverse[currentAxis.upperBound] - scrollParentsUpperBound;
 
  let placementRefBounds: { upper: number; lower: number } | undefined;
  if (spaceReverse < contentsSize && spaceRegular < contentsSize) {
    // If there would not be enough room in both directions, always prefer regular / scroll (down, end) direction,
    // since this way the element can expand and scroll while this cannot happen if there's not enough room in front.
    responsiveDirection = actualRtl ? currentAxis.directionReverse : currentAxis.directionRegular;
  } else Iif (minSpaceThresholdFactor) {
    const contentsSizeWithThreshold = contentsSize + minSpaceThresholdFactor * contentsSize;
    if (spaceReverse < contentsSizeWithThreshold && spaceRegular < contentsSizeWithThreshold) {
      // If a threshold is set and there would not be enough space including the threshold in both directions
      // use the direction with more space
      if (spaceReverse < spaceRegular) {
        responsiveDirection = currentAxis.directionRegular;
      } else {
        responsiveDirection = currentAxis.directionReverse;
      }
    } else if (spaceReverse < contentsSizeWithThreshold) {
      responsiveDirection = currentAxis.directionRegular;
    } else Iif (spaceRegular < contentsSizeWithThreshold) {
      responsiveDirection = currentAxis.directionReverse;
    }
  }
  Iif (!responsiveDirection) {
    if (spaceReverse < contentsSize) {
      responsiveDirection = currentAxis.directionRegular;
    } else if (spaceRegular < contentsSize) {
      responsiveDirection = currentAxis.directionReverse;
    } else {
      if (
        responsiveDirectionToPlacement &&
        placementReferenceElement &&
        hostElement !== placementReferenceElement
      ) {
        placementRefBounds = calculatePlacementRefOuterBounds(
          currentAxis,
          placementReferenceElement
        );
        responsiveDirection = calculateDirectionFromPlacementRef({
          currentAxis,
          positionRegular,
          positionReverse,
          contentSize: contentsSize,
          placementRefBounds,
          currentDirection: actualCurrentDirection,
          rtl: actualRtl
        });
      } else {
        // If there would be enough room in both directions, use the set direction (or the regular one if not set).
        responsiveDirection = actualCurrentDirection;
      }
    }
  }
 
  let close = false;
  Iif (isScrolling) {
    // Check if the container host or placement reference is hidden and close the component. (Mostly done when scrolling.)
    Iif (
      closeOnPlacementReferenceScrollOut &&
      placementReferenceElement &&
      hostElement !== placementReferenceElement
    ) {
      placementRefBounds ??= calculatePlacementRefOuterBounds(
        currentAxis,
        placementReferenceElement
      );
      const placementRefRect = placementReferenceElement.getBoundingClientRect();
      // A number showing how many visible pixels of the placement ref would be shown in reverse (up, start) direction
      const placementRefVisibleTop =
        placementRefRect[currentAxis.lowerBound] - placementRefBounds.upper;
      // A number showing how many visible pixels of the placement ref would be shown in regular / scroll (down, end) direction
      const placementRefVisibleBottom =
        placementRefBounds.lower - placementRefRect[currentAxis.upperBound];
      Iif (placementRefVisibleTop < 0 || placementRefVisibleBottom < 0) {
        // Close the component if the placement ref is not visible.
        close = true;
      }
    }
    Iif (!close && closeOnContentScrollOut) {
      // A number showing how many visible pixels would be available the other way if set to regular / scroll (down, end) direction
      const spaceRegularOtherSide =
        scrollParentsLowerBound - positionReverse[currentAxis.upperBound];
      // A number showing how many visible pixels would be available the other way if set to reverse (up, start) direction
      const spaceReverseOtherSide =
        positionRegular[currentAxis.upperBound] - scrollParentsUpperBound;
      Iif (spaceRegularOtherSide < 0 || spaceReverseOtherSide < 0) {
        // Close the component if there is not enough space even in the other direction.
        close = true;
      }
    }
  }
  responsiveDirection = actualRtl
    ? responsiveDirection === 'start'
      ? 'end'
      : responsiveDirection === 'end'
        ? 'start'
        : responsiveDirection
    : responsiveDirection;
  return { responsiveDirection, close };
};