{"version":3,"sources":["../src/createPositionManager.ts"],"sourcesContent":["import { computePosition } from '@floating-ui/dom';\nimport type { Middleware, Placement, Strategy } from '@floating-ui/dom';\nimport { isHTMLElement } from '@fluentui/react-utilities';\nimport type { OnPositioningEndEventDetail, PositionManager, PositioningPlacement, TargetElement } from './types';\nimport { debounce, writeArrowUpdates, writeContainerUpdates } from './utils';\nimport { listScrollParents } from './utils/listScrollParents';\nimport { POSITIONING_END_EVENT } from './constants';\nimport { createResizeObserver } from './utils/createResizeObserver';\n\ninterface PositionManagerOptions {\n  /**\n   * The positioned element\n   */\n  container: HTMLElement;\n  /**\n   * Element that the container will be anchored to\n   */\n  target: TargetElement;\n  /**\n   * Arrow that points from the container to the target\n   */\n  arrow: HTMLElement | null;\n  /**\n   * The value of the css `position` property\n   * @default absolute\n   */\n  strategy: Strategy;\n  /**\n   * [Floating UI middleware](https://floating-ui.com/docs/middleware)\n   */\n  middleware: Middleware[];\n  /**\n   * [Floating UI placement](https://floating-ui.com/docs/computePosition#placement)\n   */\n  placement?: Placement;\n  /**\n   * Modifies whether popover is positioned using transform.\n   * @default true\n   */\n  useTransform?: boolean;\n  /**\n   * Disables the resize observer that updates position on target or dimension change\n   */\n  disableUpdateOnResize?: boolean;\n}\n\nfunction isLayoutViewportUnavailable(container: HTMLElement): boolean {\n  const { clientWidth, clientHeight } = container.ownerDocument.documentElement;\n\n  return clientWidth === 0 && clientHeight === 0;\n}\n\n/**\n * @internal\n * @returns manager that handles positioning out of the react lifecycle\n */\nexport function createPositionManager(options: PositionManagerOptions): PositionManager {\n  let isDestroyed = false;\n  const {\n    container,\n    target,\n    arrow,\n    strategy,\n    middleware,\n    placement,\n    useTransform = true,\n    disableUpdateOnResize = false,\n  } = options;\n  const targetWindow = container.ownerDocument.defaultView;\n  if (!target || !container || !targetWindow) {\n    return {\n      updatePosition: () => undefined,\n      dispose: () => undefined,\n    };\n  }\n\n  // When the dimensions of the target or the container change - trigger a position update\n  const resizeObserver = disableUpdateOnResize\n    ? null\n    : createResizeObserver(targetWindow, entries => {\n        // If content rect dimensions to go 0 -> very likely that `display: none` is being used to hide the element\n        // In this case don't update and let users update imperatively\n        const shouldUpdateOnResize = entries.every(entry => {\n          return entry.contentRect.width > 0 && entry.contentRect.height > 0;\n        });\n\n        if (shouldUpdateOnResize) {\n          updatePosition();\n        }\n      });\n\n  let isFirstUpdate = true;\n  const scrollParents: Set<HTMLElement> = new Set<HTMLElement>();\n\n  // When the container is first resolved, set position `fixed` to avoid scroll jumps.\n  // Without this scroll jumps can occur when the element is rendered initially and receives focus\n  Object.assign(container.style, { position: 'fixed', left: 0, top: 0, margin: 0 });\n\n  const forceUpdate = () => {\n    // debounced update can still occur afterwards\n    // early return to avoid memory leaks\n    if (isDestroyed) {\n      return;\n    }\n\n    if (isFirstUpdate) {\n      listScrollParents(container).forEach(scrollParent => scrollParents.add(scrollParent));\n      if (isHTMLElement(target)) {\n        listScrollParents(target).forEach(scrollParent => scrollParents.add(scrollParent));\n      }\n\n      scrollParents.forEach(scrollParent => {\n        scrollParent.addEventListener('scroll', updatePosition, { passive: true });\n      });\n\n      resizeObserver?.observe(container);\n      if (isHTMLElement(target)) {\n        resizeObserver?.observe(target);\n      }\n\n      isFirstUpdate = false;\n    }\n\n    Object.assign(container.style, { position: strategy });\n    computePosition(target, container, { placement, middleware, strategy })\n      .then(({ x, y, middlewareData, placement: computedPlacement }) => {\n        // Promise can still resolve after destruction\n        // early return to avoid applying outdated position\n        if (isDestroyed) {\n          return;\n        }\n\n        const positioningMiddlewareData = isLayoutViewportUnavailable(container)\n          ? {\n              ...middlewareData,\n              hide: { ...middlewareData.hide, escaped: false, referenceHidden: false },\n            }\n          : middlewareData;\n\n        writeArrowUpdates({ arrow, middlewareData: positioningMiddlewareData });\n        writeContainerUpdates({\n          container,\n          middlewareData: positioningMiddlewareData,\n          placement: computedPlacement,\n          coordinates: { x, y },\n          lowPPI: (targetWindow?.devicePixelRatio || 1) <= 1,\n          strategy,\n          useTransform,\n        });\n\n        container.dispatchEvent(\n          new CustomEvent<OnPositioningEndEventDetail>(POSITIONING_END_EVENT, {\n            detail: {\n              // Cast from Floating UI's Placement to the Fluent-owned PositioningPlacement.\n              // These are equivalent string unions; the cast avoids leaking @floating-ui/dom\n              // types into the public API surface.\n              placement: computedPlacement satisfies PositioningPlacement,\n              escaped: positioningMiddlewareData.hide?.escaped ?? false,\n              referenceHidden: positioningMiddlewareData.hide?.referenceHidden ?? false,\n            },\n          }),\n        );\n      })\n      .catch(err => {\n        // https://github.com/floating-ui/floating-ui/issues/1845\n        // FIXME for node > 14\n        // node 15 introduces promise rejection which means that any components\n        // tests need to be `it('', async () => {})` otherwise there can be race conditions with\n        // JSDOM being torn down before this promise is resolved so globals like `window` and `document` don't exist\n        // Unless all tests that ever use `usePositioning` are turned into async tests, any logging during testing\n        // will actually be counter productive\n        if (process.env.NODE_ENV === 'development') {\n          // eslint-disable-next-line no-console\n          console.error('[usePositioning]: Failed to calculate position', err);\n        }\n      });\n  };\n\n  const updatePosition = debounce(() => forceUpdate());\n\n  const dispose = () => {\n    isDestroyed = true;\n\n    if (targetWindow) {\n      targetWindow.removeEventListener('scroll', updatePosition);\n      targetWindow.removeEventListener('resize', updatePosition);\n    }\n\n    scrollParents.forEach(scrollParent => {\n      scrollParent.removeEventListener('scroll', updatePosition);\n    });\n    scrollParents.clear();\n\n    resizeObserver?.disconnect();\n  };\n\n  if (targetWindow) {\n    targetWindow.addEventListener('scroll', updatePosition, { passive: true });\n    targetWindow.addEventListener('resize', updatePosition);\n  }\n\n  // Update the position on initialization\n  updatePosition();\n\n  return {\n    updatePosition,\n    dispose,\n  };\n}\n"],"names":["computePosition","isHTMLElement","debounce","writeArrowUpdates","writeContainerUpdates","listScrollParents","POSITIONING_END_EVENT","createResizeObserver","isLayoutViewportUnavailable","container","clientWidth","clientHeight","ownerDocument","documentElement","createPositionManager","options","isDestroyed","target","arrow","strategy","middleware","placement","useTransform","disableUpdateOnResize","targetWindow","defaultView","updatePosition","undefined","dispose","resizeObserver","entries","shouldUpdateOnResize","every","entry","contentRect","width","height","isFirstUpdate","scrollParents","Set","Object","assign","style","position","left","top","margin","forceUpdate","forEach","scrollParent","add","addEventListener","passive","observe","then","x","y","middlewareData","computedPlacement","positioningMiddlewareData","hide","escaped","referenceHidden","coordinates","lowPPI","devicePixelRatio","dispatchEvent","CustomEvent","detail","catch","err","process","env","NODE_ENV","console","error","removeEventListener","clear","disconnect"],"mappings":";;;;+BAwDgBc;;;;;;qBAxDgB,mBAAmB;gCAErB,4BAA4B;uBAES,mBAAU;mCAC3C,+BAA4B;2BACxB,iBAAc;sCACf,kCAA+B;AAuCpE,SAASN,4BAA4BC,SAAsB;IACzD,MAAM,EAAEC,WAAW,EAAEC,YAAY,EAAE,GAAGF,UAAUG,aAAa,CAACC,eAAe;IAE7E,OAAOH,gBAAgB,KAAKC,iBAAiB;AAC/C;AAMO,+BAA+BI,OAA+B;IACnE,IAAIC,cAAc;IAClB,MAAM,EACJP,SAAS,EACTQ,MAAM,EACNC,KAAK,EACLC,QAAQ,EACRC,UAAU,EACVC,SAAS,EACTC,eAAe,IAAI,EACnBC,wBAAwB,KAAK,EAC9B,GAAGR;IACJ,MAAMS,eAAef,UAAUG,aAAa,CAACa,WAAW;IACxD,IAAI,CAACR,UAAU,CAACR,aAAa,CAACe,cAAc;QAC1C,OAAO;YACLE,gBAAgB,IAAMC;YACtBC,SAAS,IAAMD;QACjB;IACF;IAEA,wFAAwF;IACxF,MAAME,iBAAiBN,wBACnB,WACAhB,0CAAAA,EAAqBiB,cAAcM,CAAAA;QACjC,2GAA2G;QAC3G,8DAA8D;QAC9D,MAAMC,uBAAuBD,QAAQE,KAAK,CAACC,CAAAA;YACzC,OAAOA,MAAMC,WAAW,CAACC,KAAK,GAAG,KAAKF,MAAMC,WAAW,CAACE,MAAM,GAAG;QACnE;QAEA,IAAIL,sBAAsB;YACxBL;QACF;IACF;IAEJ,IAAIW,gBAAgB;IACpB,MAAMC,gBAAkC,IAAIC;I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