From 1bc7b7dc0ed602e882835940cea1f44de65160ea Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Wed, 11 Nov 2026 20:16:43 -0800 Subject: [PATCH 1/3] ci: drop Storybook GitHub Pages deploy Pages can't be published for this repo; docs run locally via `npm start`. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docs.yml | 34 ---------------------------------- README.md | 6 ++---- 2 files changed, 2 insertions(+), 38 deletions(-) delete mode 100644 .github/workflows/docs.yml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml deleted file mode 100644 index 9b89eaf62..000000000 --- a/.github/workflows/docs.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Docs - -on: - push: - branches: [master] - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: pages - cancel-in-progress: true - -jobs: - deploy: - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version-file: .nvmrc - cache: npm - - run: npm ci && npm run build:docs - - uses: actions/upload-pages-artifact@v5 - with: - path: build - - id: deployment - uses: actions/deploy-pages@v5 diff --git a/README.md b/README.md index 4eeee3ca4..7dffef425 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ These libraries are not bundled with Reactstrap and required at runtime: ## About the Project -This library contains React Bootstrap components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript. However, [Popper](https://popper.js.org/) (`@popperjs/core`) is relied upon for advanced positioning of content like Tooltips, Popovers, and auto-flipping Dropdowns. +This library contains React Bootstrap components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript. However, [Floating UI](https://floating-ui.com/) (`@floating-ui/react-dom`) is relied upon for advanced positioning of content like Tooltips, Popovers, and auto-flipping Dropdowns. There are a few core concepts to understand in order to make the most out of this library. @@ -94,7 +94,7 @@ There are a few core concepts to understand in order to make the most out of thi ## Documentation -Storybook docs are deployed to this repo's GitHub Pages by `.github/workflows/docs.yml` (`npm start` locally). +Storybook docs are not hosted; run them locally with `npm start`. Upstream v9 docs: https://reactstrap.github.io ## [Contributing](CONTRIBUTING.md) @@ -124,8 +124,6 @@ npm publish # prepublishOnly runs typecheck, lint, tests a git push --follow-tags ``` -Storybook docs deploy to GitHub Pages on every push to `master`. - ## In the wild Organizations and projects using `reactstrap` From d7fe6d1aec4f4c8de6ebbcd965f0f048fc233656 Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Wed, 11 Nov 2026 20:16:43 -0800 Subject: [PATCH 2/3] feat!: replace Popper with Floating UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @popperjs/core is unmaintained since 2023. Tooltip, Popover and DropdownMenu now call `useFloating` from @floating-ui/react-dom directly; the react-popper style `popper.tsx` shim is gone. BREAKING CHANGE: `PopperContent` → `FloatingContent`, `popperClassName` → `floatingClassName`, `modifiers` → `middleware`, `boundariesElement` → `boundary`, `offset` takes Floating UI `OffsetOptions` (Popover default 8). `data-popper-reference-hidden` and `Util.PopperPlacements` are removed. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 +- CHANGELOG.md | 17 + package-lock.json | 53 ++- package.json | 2 +- src/Dropdown.tsx | 39 ++- src/DropdownContext.ts | 2 + src/DropdownMenu.tsx | 133 +++++--- src/DropdownToggle.tsx | 51 ++- src/FloatingContent.tsx | 308 ++++++++++++++++++ src/Popover.tsx | 10 +- src/PopperContent.tsx | 243 -------------- src/Tooltip.tsx | 4 +- src/TooltipPopoverWrapper.tsx | 50 +-- src/__mocks__/popper.tsx | 29 -- src/__tests__/ButtonDropdown.spec.tsx | 2 - src/__tests__/Dropdown.spec.tsx | 4 +- src/__tests__/DropdownMenu.spec.tsx | 72 ++-- src/__tests__/DropdownToggle.spec.tsx | 2 - ...tent.spec.tsx => FloatingContent.spec.tsx} | 221 +++++++------ src/__tests__/Popover.spec.tsx | 46 ++- src/__tests__/Tooltip.spec.tsx | 36 +- src/__tests__/TooltipPopoverWrapper.spec.tsx | 79 ++--- src/__tests__/Uncontrolled.spec.tsx | 2 - ...ic.popper.tsx => polymorphic.floating.tsx} | 20 +- src/__tests__/setup.ts | 6 + src/__tests__/typings.tsx | 4 +- src/index.ts | 7 +- src/popper.tsx | 206 ------------ src/testUtils.tsx | 11 + src/utils.ts | 18 - stories/Upgrading.mdx | 4 +- tsconfig.build.json | 2 +- v10-migration.md | 2 + vite.config.ts | 2 +- 34 files changed, 824 insertions(+), 872 deletions(-) create mode 100644 src/FloatingContent.tsx delete mode 100644 src/PopperContent.tsx delete mode 100644 src/__mocks__/popper.tsx rename src/__tests__/{PopperContent.spec.tsx => FloatingContent.spec.tsx} (50%) rename src/__tests__/{polymorphic.popper.tsx => polymorphic.floating.tsx} (88%) delete mode 100644 src/popper.tsx diff --git a/AGENTS.md b/AGENTS.md index cf7235e71..5349dbef1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ Guidance for coding agents working in this repo. ## What this is `reactstrap` v10 (fork): stateless-ish React 19 components rendering Bootstrap 5 markup. No Bootstrap JS, no jQuery. -Positioning via `@popperjs/core`. Bootstrap 6 is out of scope (separate migration). +Positioning via Floating UI (`@floating-ui/react-dom`, `useFloating` called directly; no Popper). Bootstrap 6 is out of scope (separate migration). ## Stack @@ -37,16 +37,17 @@ CI (`.github/workflows/ci.yml`) runs lint, format:check, typecheck, cover, build - `src/index.ts` — the public barrel. Anything not exported here is internal. - `src/utils.ts` — shared helpers and shared types (`CSSModule`, `Tag`, `Target`, `InnerRef`). Exposed as `Util`. - `src/Transition.tsx` — internal replacement for `react-transition-group` (`Transition`, `useNodeRef`). -- `src/popper.tsx` — internal replacement for `react-popper` (`Manager`, `Reference`, `Popper`). +- `src/FloatingContent.tsx` — positioned tooltip/popover body; `DropdownMenu` floats against the toggle from `DropdownContext.reference`. - `src/*Context.ts` — typed React contexts. - `src/__tests__/*.spec.tsx` — Vitest specs; `typings.tsx` and `polymorphic.*.tsx` are compile-only type tests. -- `src/__mocks__/popper.tsx` — used via `vi.mock('../popper')`. +- `src/__tests__/setup.ts` spies `useFloating` (real implementation); assert options with `lastFloating()` / `middleware(name)` from `src/testUtils.tsx`. - `stories/` — Storybook docs; `@conventioncatcorp/reactstrap` resolves to `src/index.ts` (tsconfig `paths` + Storybook alias). ## Conventions - No `prop-types`, no `defaultProps` on function components (React 19 ignores them). Defaults live in destructuring. - Class components may keep `static defaultProps`; `PopperContent.defaultProps` is public API (apps patch `offset`). + Class components may keep `static defaultProps`; `FloatingContent.defaultProps` is public API (apps patch `offset`). +- `data-popper-placement` / `data-bs-popper` attributes are Bootstrap 5 CSS hooks, not Popper: keep them. - No index signatures on props. Components with `tag`: `XOwnProps` + `XProps = XOwnProps & PolymorphicExtras` (spell `XOwnProps` out, or Storybook docgen loses the props table); classes use `PolymorphicClassExtras` and `declare props: XProps`. Add ok/`@ts-expect-error` cases to diff --git a/CHANGELOG.md b/CHANGELOG.md index 3baed29d6..780b54dbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,20 @@ +# 11.0.0 (unreleased) + +Positioning moves from `@popperjs/core` (unmaintained since 2023) to [Floating UI](https://floating-ui.com/) +(`@floating-ui/react-dom`). Breaking: + +- `PopperContent` → `FloatingContent` (`PopperContentProps` → `FloatingContentProps`). Patch defaults with + `FloatingContent.defaultProps.offset = 5`. +- `popperClassName` → `floatingClassName` (Tooltip, Popover, FloatingContent). +- `modifiers` → `middleware` (Floating UI `Middleware[]`; same-named entries replace the defaults `offset`, `flip`, + `shift`). +- `offset: [skidding, distance]` → Floating UI `OffsetOptions`: `[0, 8]` becomes `8`, `[x, y]` becomes + `{ mainAxis: y, crossAxis: x }`. Popover defaults to `8`. +- `boundariesElement` → `boundary` (Floating UI `Boundary`, default `'clippingAncestors'`). +- `placement` / `strategy` use Floating UI types; `auto`, `auto-start` and `auto-end` still work (via `autoPlacement`). +- Removed: `data-popper-reference-hidden` attribute, `Util.PopperPlacements`. +- `DropdownToggle` `innerRef` now also works inside a navbar. + # 10.0.0 (2026-11-10) First release of `@conventioncatcorp/reactstrap`, the ConventionCatCorp fork. TypeScript, React 19 and Bootstrap 5 diff --git a/package-lock.json b/package-lock.json index ded9805df..f07e9fbe0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { - "name": "reactstrap", - "version": "9.2.3", + "name": "@conventioncatcorp/reactstrap", + "version": "10.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "reactstrap", - "version": "9.2.3", + "name": "@conventioncatcorp/reactstrap", + "version": "10.0.0", "license": "MIT", "dependencies": { - "@popperjs/core": "^2.11.8", + "@floating-ui/react-dom": "^2.1.9", "classnames": "^2.5.1" }, "devDependencies": { @@ -810,6 +810,44 @@ } } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, "node_modules/@joshwooding/vite-plugin-react-docgen-typescript": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@joshwooding/vite-plugin-react-docgen-typescript/-/vite-plugin-react-docgen-typescript-0.7.0.tgz", @@ -1976,7 +2014,9 @@ "version": "2.11.8", "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "dev": true, "license": "MIT", + "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -4817,7 +4857,6 @@ "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -4859,7 +4898,6 @@ "version": "19.3.1", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", - "dev": true, "license": "MIT", "dependencies": { "scheduler": "^0.28.0" @@ -5015,7 +5053,6 @@ "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", - "dev": true, "license": "MIT" }, "node_modules/semver": { diff --git a/package.json b/package.json index 8a90c2890..683d06f51 100644 --- a/package.json +++ b/package.json @@ -266,7 +266,7 @@ } }, "dependencies": { - "@popperjs/core": "^2.11.8", + "@floating-ui/react-dom": "^2.1.9", "classnames": "^2.5.1" }, "peerDependencies": { diff --git a/src/Dropdown.tsx b/src/Dropdown.tsx index e8cee6ee8..d61907c58 100644 --- a/src/Dropdown.tsx +++ b/src/Dropdown.tsx @@ -15,7 +15,6 @@ import { type SyntheticEvent, } from 'react'; import classNames from 'classnames'; -import { Manager } from './popper'; import { DropdownContext, type DropdownContextValue, @@ -52,7 +51,7 @@ export interface DropdownOwnProps { cssModule?: CSSModule; /** Shorthand for `direction="up"` (only when direction is `down`). */ dropup?: boolean; - /** Render the menu without popper (static positioning). */ + /** Render the menu statically (no floating positioning). */ inNavbar?: boolean; /** Add `.active` when an item of the second child (the menu) is active. */ setActiveFromChild?: boolean; @@ -107,13 +106,15 @@ function keyCodeOf(e: { which: number; key?: string }): number { } class Dropdown extends Component< - DropdownProps + DropdownProps, + { reference: HTMLElement | null } > { // Not `Readonly

`: lets JSX infer `T` from a string `tag` (else it widens to `ElementType`). declare props: DropdownProps; static override contextType = InputGroupContext; declare context: ContextType; + override state = { reference: null as HTMLElement | null }; containerRef = createRef(); menuRef = createRef(); toggleRef = createRef(); @@ -137,6 +138,7 @@ class Dropdown extends Component< handleToggleRef = (el: HTMLElement | null) => { this.toggleRef.current = el; + if (el !== this.state.reference) this.setState({ reference: el }); }; handleDocumentClick = (e: Event) => { @@ -259,6 +261,7 @@ class Dropdown extends Component< // Called by DropdownMenu with its DOM node onMenuRef: this.handleMenuRef, onToggleRef: this.handleToggleRef, + reference: this.state.reference, menuRole: this.props.menuRole, }; } @@ -355,29 +358,25 @@ class Dropdown extends Component< if (this.context.insideInputGroup) { return ( - - {Children.map(this.props.children, (child) => - cloneElement(child as ReactElement, { - onKeyDown: this.handleKeyDown, - }), - )} - + {Children.map(this.props.children, (child) => + cloneElement(child as ReactElement, { + onKeyDown: this.handleKeyDown, + }), + )} ); } return ( - - - + ); } diff --git a/src/DropdownContext.ts b/src/DropdownContext.ts index 7c6b562fc..9f7726692 100644 --- a/src/DropdownContext.ts +++ b/src/DropdownContext.ts @@ -12,6 +12,8 @@ export interface DropdownContextValue { /** DropdownMenu reports its DOM node, so outside clicks close the dropdown. */ onMenuRef?: (el: HTMLElement | null) => void; onToggleRef?: (el: HTMLElement | null) => void; + /** The toggle's DOM node; DropdownMenu floats against it. */ + reference?: HTMLElement | null; menuRole?: 'listbox' | 'menu' | boolean; } diff --git a/src/DropdownMenu.tsx b/src/DropdownMenu.tsx index df928afab..b24c70a4c 100644 --- a/src/DropdownMenu.tsx +++ b/src/DropdownMenu.tsx @@ -1,16 +1,24 @@ import { Component, + useCallback, type ContextType, type CSSProperties, type ElementType, type HTMLAttributes, + type MouseEvent, type ReactNode, } from 'react'; import { createPortal } from 'react-dom'; import classNames from 'classnames'; -import type { Placement, PositioningStrategy } from '@popperjs/core'; -import { Popper } from './popper'; -import type { PopperModifier } from './PopperContent'; +import { + autoUpdate, + flip as flipMiddleware, + shift, + useFloating, + type Middleware, + type Placement, + type Strategy, +} from '@floating-ui/react-dom'; import { DropdownContext, type DropdownDirection } from './DropdownContext'; import { getTarget, @@ -29,14 +37,15 @@ export interface DropdownMenuOwnProps { end?: boolean; /** Flips the menu to the opposite side if there is not enough space to fit */ flip?: boolean; - modifiers?: PopperModifier[]; + /** Extra Floating UI middleware; same-named ones replace the defaults (`flip`, `shift`). */ + middleware?: Middleware[]; cssModule?: CSSModule; /** Keep the menu mounted (and positioned) while closed. */ persist?: boolean; - strategy?: PositioningStrategy; + strategy?: Strategy; /** Portal the menu into this element. */ container?: Target; - /** Update popper layout when a click event comes up. This leverages event bubbling. */ + /** Reposition the menu on click inside it (e.g. when an item changes its size). */ updateOnSelect?: boolean; } @@ -53,6 +62,67 @@ const directionPositionMap: Record = { down: 'bottom', }; +type FloatingMenuProps = HTMLAttributes & { + tag: ElementType; + reference: Element | null; + placement: Placement; + flip: boolean; + middleware: Middleware[]; + strategy?: Strategy; + updateOnSelect?: boolean; + onMenuRef?: (el: HTMLElement | null) => void; +}; + +function FloatingMenu({ + tag: Tag, + reference, + placement, + flip, + middleware, + strategy, + updateOnSelect, + onMenuRef, + style, + onClick, + ...attrs +}: FloatingMenuProps) { + const names = new Set(middleware.map((m) => m.name)); + const floating = useFloating({ + elements: { reference }, + placement, + strategy, + middleware: [ + ...[flip && flipMiddleware(), shift()].filter( + (m): m is Middleware => !!m && !names.has(m.name), + ), + ...middleware, + ], + whileElementsMounted: autoUpdate, + }); + const { setFloating } = floating.refs; + const ref = useCallback( + (el: HTMLElement | null) => { + setFloating(el); + // Lets Dropdown ignore clicks inside the menu. + onMenuRef?.(el); + }, + [setFloating, onMenuRef], + ); + + return ( + ) => { + onClick?.(e); + if (updateOnSelect) floating.update(); + }} + /> + ); +} + class DropdownMenu extends Component< DropdownMenuProps > { @@ -73,7 +143,7 @@ class DropdownMenu extends Component< end, tag: Tag = 'div', flip = true, - modifiers = [], + middleware = [], persist, strategy, container, @@ -83,7 +153,7 @@ class DropdownMenu extends Component< tag?: ElementType; placement?: string; } & HTMLAttributes; - const { isOpen, inNavbar, direction, onMenuRef } = this.context; + const { isOpen, inNavbar, direction, onMenuRef, reference } = this.context; const classes = mapToCssModules( classNames(className, 'dropdown-menu', { @@ -101,41 +171,28 @@ class DropdownMenu extends Component< ? { display: 'block', visibility: isOpen ? 'visible' : 'hidden' } : {}; - const popper = ( - - {({ ref, style, placement, update }) => { - const handleRef = (el: HTMLElement | null) => { - // Send the ref to popper - ref(el); - // Send the ref to the parent Dropdown so that clicks outside - // it will cause it to close - onMenuRef?.(el); - }; - - return ( - updateOnSelect && update()} - /> - ); - }} - + updateOnSelect={updateOnSelect} + onMenuRef={onMenuRef} + style={{ ...attrs.style, ...persistStyles }} + aria-hidden={!isOpen} + className={classes} + /> ); return container - ? createPortal(popper, getTarget(container) as Element) - : popper; + ? createPortal(menu, getTarget(container) as Element) + : menu; } return ( diff --git a/src/DropdownToggle.tsx b/src/DropdownToggle.tsx index c2d912ef2..c05c2caca 100644 --- a/src/DropdownToggle.tsx +++ b/src/DropdownToggle.tsx @@ -8,7 +8,6 @@ import { type Ref, } from 'react'; import classNames from 'classnames'; -import { Reference } from './popper'; import { DropdownContext } from './DropdownContext'; import { mapToCssModules, @@ -68,6 +67,14 @@ class DropdownToggle extends Component< this.context.toggle(e); }; + // Stable, so React only calls it on mount/unmount. + handleRef = (el: HTMLElement | null) => { + const { innerRef } = this.props; + if (typeof innerRef === 'function') innerRef(el); + else if (innerRef) innerRef.current = el; + this.context.onToggleRef?.(el); + }; + getRole() { return this.context.menuRole || (this.props['aria-haspopup'] ?? true); } @@ -81,7 +88,7 @@ class DropdownToggle extends Component< split, nav, tag, - innerRef, + innerRef: _innerRef, ...props } = this.props as DropdownToggleImplProps; const ariaLabel = props['aria-label'] || 'Toggle Dropdown'; @@ -112,33 +119,19 @@ class DropdownToggle extends Component< Tag = tag; } - const renderTag = ({ ref }: { ref?: (el: HTMLElement | null) => void }) => { - const handleRef = (el: HTMLElement | null) => { - ref?.(el); - this.context.onToggleRef?.(el); - }; - - return ( - - {children} - - ); - }; - - // No Reference component if the component is in Navbar - if (this.context.inNavbar) { - return renderTag({ ref: this.context.onToggleRef }); - } - - return {renderTag}; + return ( + + {children} + + ); } } diff --git a/src/FloatingContent.tsx b/src/FloatingContent.tsx new file mode 100644 index 000000000..5ab556c8d --- /dev/null +++ b/src/FloatingContent.tsx @@ -0,0 +1,308 @@ +import { + Component, + useState, + type ElementType, + type HTMLAttributes, + type ReactNode, +} from 'react'; +import { createPortal } from 'react-dom'; +import classNames from 'classnames'; +import { + arrow, + autoPlacement, + autoUpdate, + flip as flipMiddleware, + offset as offsetMiddleware, + shift, + useFloating, + type Alignment, + type Boundary, + type Middleware, + type OffsetOptions, + type Placement, + type Strategy, +} from '@floating-ui/react-dom'; +import { + getTarget, + mapToCssModules, + type CSSModule, + type PolymorphicClassExtras, + type Target, +} from './utils'; +import Fade, { type FadeProps } from './Fade'; + +/** Floating UI placement, plus `auto*` (best fitting side, via `autoPlacement`). */ +export type FloatingPlacement = Placement | 'auto' | `auto-${Alignment}`; + +/** Defaults applied by React. Mutable on purpose: apps may patch e.g. `FloatingContent.defaultProps.offset`. */ +export interface FloatingContentDefaultProps { + boundary: Boundary; + placement: FloatingPlacement; + hideArrow: boolean; + isOpen: boolean; + offset: OffsetOptions; + flip: boolean; + container: Target; + middleware: Middleware[]; + onClosed: () => void; + fade: boolean; + transition: FadeProps; +} + +export interface FloatingContentOwnProps { + children: ReactNode | ((args: { update: () => void }) => ReactNode); + /** Element the floating element is positioned against. */ + target: Target; + /** Where to portal the floating element; `'inline'` renders in place. */ + container?: Target; + floatingClassName?: string; + placement?: FloatingPlacement; + /** Adds `${placementPrefix}-auto` to the floating element. */ + placementPrefix?: string; + arrowClassName?: string; + hideArrow?: boolean; + isOpen?: boolean; + cssModule?: CSSModule; + /** Distance from the target (`offset` middleware). */ + offset?: OffsetOptions; + /** Placements to try when `flip`ping. */ + fallbackPlacements?: Placement[]; + /** Flip to the opposite side when it would overflow. */ + flip?: boolean; + /** Extra Floating UI middleware; same-named ones replace the defaults (`offset`, `flip`, `shift`). */ + middleware?: Middleware[]; + strategy?: Strategy; + /** Clipping boundary for `shift`. */ + boundary?: Boundary; + onClosed?: () => void; + /** Animate with Fade. */ + fade?: boolean; + /** Props for the Fade transition. */ + transition?: FadeProps; +} + +/** Props of `FloatingContent`; extra props (typed by `tag`, default `div`) go to the Fade wrapper. */ +export type FloatingContentProps = + FloatingContentOwnProps & PolymorphicClassExtras; + +interface FloatingContentState { + isOpen?: boolean; +} + +type ResolvedProps = FloatingContentOwnProps & + FloatingContentDefaultProps & + Omit, 'children'> & { tag?: ElementType }; + +type FloatingProps = Pick< + ResolvedProps, + | 'children' + | 'placement' + | 'offset' + | 'flip' + | 'fallbackPlacements' + | 'boundary' + | 'middleware' + | 'strategy' + | 'hideArrow' + | 'arrowClassName' +> & { reference: Element | null; className: string }; + +function Floating({ + reference, + placement, + offset, + flip, + fallbackPlacements, + boundary, + middleware, + strategy, + hideArrow, + className, + arrowClassName, + children, +}: FloatingProps) { + const [arrowElement, setArrowElement] = useState(null); + const [side, alignment] = placement.split('-') as [string, Alignment?]; + const auto = side === 'auto'; + const names = new Set(middleware.map((m) => m.name)); + const defaults = [ + offsetMiddleware(offset), + auto + ? autoPlacement({ alignment }) + : flip && flipMiddleware({ fallbackPlacements }), + shift({ boundary }), + ].filter((m): m is Middleware => !!m && !names.has(m.name)); + + const { + refs, + floatingStyles, + isPositioned, + middlewareData, + update, + placement: actualPlacement, + } = useFloating({ + elements: { reference }, + placement: auto ? undefined : (placement as Placement), + strategy, + middleware: [ + ...defaults, + ...middleware, + arrowElement && arrow({ element: arrowElement }), + ], + whileElementsMounted: autoUpdate, + }); + const { setFloating } = refs; + const arrowData = middlewareData.arrow; + + return ( +

+ {typeof children === 'function' ? children({ update }) : children} + {!hideArrow && ( + + )} +
+ ); +} + +class FloatingContent extends Component< + FloatingContentProps, + FloatingContentState +> { + // Not `Readonly

`: lets JSX infer `T` from a string `tag` (else it widens to `ElementType`). + declare props: FloatingContentProps; + static defaultProps: FloatingContentDefaultProps = { + boundary: 'clippingAncestors', + placement: 'auto', + hideArrow: false, + isOpen: false, + offset: 0, + flip: true, + container: 'body', + middleware: [], + onClosed: () => {}, + fade: true, + transition: {}, + }; + + private element: HTMLDivElement | null = null; + + constructor(props: FloatingContentProps) { + super(props); + this.state = { isOpen: props.isOpen }; + } + + static getDerivedStateFromProps( + props: { isOpen?: boolean }, + state: FloatingContentState, + ): FloatingContentState | null { + return props.isOpen && !state.isOpen ? { isOpen: props.isOpen } : null; + } + + override componentDidUpdate() { + const child = this.element?.childNodes[0] as HTMLElement | undefined; + child?.focus?.(); + } + + onClosed = () => { + (this.props as ResolvedProps).onClosed(); + this.setState({ isOpen: false }); + }; + + getRef = (el: HTMLDivElement | null) => { + this.element = el; + }; + + renderChildren(reference: Element | null) { + const { + cssModule, + isOpen, + target: _target, + placementPrefix, + arrowClassName, + floatingClassName, + tag, + container: _container, + onClosed: _onClosed, + fade, + transition, + children, + placement, + offset, + flip, + fallbackPlacements, + boundary, + middleware, + strategy, + hideArrow, + ...attrs + } = this.props as ResolvedProps; + + return ( + + + + ); + } + + override render() { + if (!this.state.isOpen) return null; + + const { target, container } = this.props as ResolvedProps; + const reference = target instanceof Element ? target : getTarget(target); + + return container === 'inline' + ? this.renderChildren(reference) + : createPortal( +

{this.renderChildren(reference)}
, + getTarget(container) as Element, + ); + } +} + +export default FloatingContent; diff --git a/src/Popover.tsx b/src/Popover.tsx index 29deba040..972730aef 100644 --- a/src/Popover.tsx +++ b/src/Popover.tsx @@ -11,8 +11,8 @@ export interface PopoverProps extends TooltipPopoverWrapperProps { placementPrefix?: string; /** @default 'click' */ trigger?: string; - /** @default [0, 8] */ - offset?: [number, number]; + /** @default 8 */ + offset?: TooltipPopoverWrapperProps['offset']; /** The underlying `TooltipPopoverWrapper` instance. */ ref?: Ref; } @@ -21,9 +21,9 @@ function Popover({ placement = 'right', placementPrefix = 'bs-popover', trigger = 'click', - offset = [0, 8], + offset = 8, arrowClassName, - popperClassName, + floatingClassName, innerClassName, ...props }: PopoverProps) { @@ -35,7 +35,7 @@ function Popover({ trigger={trigger} offset={offset} arrowClassName={classNames('popover-arrow', arrowClassName)} - popperClassName={classNames('popover', 'show', popperClassName)} + floatingClassName={classNames('popover', 'show', floatingClassName)} innerClassName={classNames('popover-inner', innerClassName)} /> ); diff --git a/src/PopperContent.tsx b/src/PopperContent.tsx deleted file mode 100644 index 774086d91..000000000 --- a/src/PopperContent.tsx +++ /dev/null @@ -1,243 +0,0 @@ -import { - Component, - type ElementType, - type HTMLAttributes, - type ReactNode, -} from 'react'; -import { createPortal } from 'react-dom'; -import classNames from 'classnames'; -import type { - Boundary, - Modifier, - Placement, - PositioningStrategy, -} from '@popperjs/core'; -import { Popper } from './popper'; -import { - getTarget, - mapToCssModules, - type CSSModule, - type PolymorphicClassExtras, - type Target, -} from './utils'; -import Fade, { type FadeProps } from './Fade'; - -export type PopperModifier = Partial>; - -/** Defaults applied by React. Mutable on purpose: apps may patch e.g. `PopperContent.defaultProps.offset`. */ -export interface PopperContentDefaultProps { - boundariesElement: Boundary | string; - placement: Placement; - hideArrow: boolean; - isOpen: boolean; - offset: [number, number]; - flip: boolean; - container: Target; - modifiers: PopperModifier[]; - onClosed: () => void; - fade: boolean; - transition: FadeProps; -} - -export interface PopperContentOwnProps { - children: ReactNode | ((args: { update: () => void }) => ReactNode); - /** Element the popper is positioned against. */ - target: Target; - /** Where to portal the popper; `'inline'` renders in place. */ - container?: Target; - popperClassName?: string; - placement?: Placement; - /** Adds `${placementPrefix}-auto` to the popper. */ - placementPrefix?: string; - arrowClassName?: string; - hideArrow?: boolean; - isOpen?: boolean; - cssModule?: CSSModule; - /** Popper `offset` modifier: `[skidding, distance]`. */ - offset?: [number, number]; - fallbackPlacements?: Placement[]; - /** Flip the popper when it would overflow. */ - flip?: boolean; - /** Extra popper modifiers; same-named ones replace the defaults. */ - modifiers?: PopperModifier[]; - strategy?: PositioningStrategy; - /** `preventOverflow` boundary. */ - boundariesElement?: Boundary | string; - onClosed?: () => void; - /** Animate with Fade. */ - fade?: boolean; - /** Props for the Fade transition. */ - transition?: FadeProps; -} - -/** Props of `PopperContent`; extra props (typed by `tag`, default `div`) go to the Fade wrapper. */ -export type PopperContentProps = - PopperContentOwnProps & PolymorphicClassExtras; - -interface PopperContentState { - isOpen?: boolean; -} - -type ResolvedProps = PopperContentOwnProps & - PopperContentDefaultProps & - Omit, 'children'> & { tag?: ElementType }; - -class PopperContent extends Component< - PopperContentProps, - PopperContentState -> { - // Not `Readonly

`: lets JSX infer `T` from a string `tag` (else it widens to `ElementType`). - declare props: PopperContentProps; - static defaultProps: PopperContentDefaultProps = { - boundariesElement: 'scrollParent', - placement: 'auto', - hideArrow: false, - isOpen: false, - offset: [0, 0], - flip: true, - container: 'body', - modifiers: [], - onClosed: () => {}, - fade: true, - transition: {}, - }; - - private element: HTMLDivElement | null = null; - - constructor(props: PopperContentProps) { - super(props); - this.state = { isOpen: props.isOpen }; - } - - static getDerivedStateFromProps( - props: { isOpen?: boolean }, - state: PopperContentState, - ): PopperContentState | null { - return props.isOpen && !state.isOpen ? { isOpen: props.isOpen } : null; - } - - override componentDidUpdate() { - const child = this.element?.childNodes[0] as HTMLElement | undefined; - child?.focus?.(); - } - - onClosed = () => { - (this.props as ResolvedProps).onClosed(); - this.setState({ isOpen: false }); - }; - - getRef = (el: HTMLDivElement | null) => { - this.element = el; - }; - - renderChildren(targetNode: Element | null) { - const { - cssModule, - children, - isOpen, - flip, - target: _target, - offset, - fallbackPlacements, - placementPrefix, - arrowClassName: _arrowClassName, - hideArrow, - popperClassName: _popperClassName, - tag, - container: _container, - modifiers, - strategy, - boundariesElement, - onClosed: _onClosed, - fade, - transition, - placement, - ...attrs - } = this.props as ResolvedProps; - const arrowClassName = mapToCssModules( - classNames('arrow', _arrowClassName), - cssModule, - ); - const popperClassName = mapToCssModules( - classNames( - _popperClassName, - placementPrefix ? `${placementPrefix}-auto` : '', - ), - cssModule, - ); - - const modifierNames = modifiers.map((m) => m.name); - const baseModifiers: PopperModifier[] = [ - { name: 'offset', options: { offset } }, - { name: 'flip', enabled: flip, options: { fallbackPlacements } }, - { name: 'preventOverflow', options: { boundary: boundariesElement } }, - ].filter((m) => !modifierNames.includes(m.name)); - - const popperTransition = { - ...transition, - baseClass: fade ? transition.baseClass : '', - timeout: fade ? transition.timeout : 0, - }; - - return ( - - - {({ - ref, - style, - placement: popperPlacement, - isReferenceHidden, - arrowProps, - update, - }) => ( -

- {typeof children === 'function' ? children({ update }) : children} - {!hideArrow && ( - - )} -
- )} - - - ); - } - - override render() { - if (!this.state.isOpen) return null; - - const { target, container } = this.props as ResolvedProps; - const targetNode = target instanceof Element ? target : getTarget(target); - - return container === 'inline' - ? this.renderChildren(targetNode) - : createPortal( -
{this.renderChildren(targetNode)}
, - getTarget(container) as Element, - ); - } -} - -export default PopperContent; diff --git a/src/Tooltip.tsx b/src/Tooltip.tsx index 9bc551263..4cfabdcf5 100644 --- a/src/Tooltip.tsx +++ b/src/Tooltip.tsx @@ -23,7 +23,7 @@ function Tooltip({ placementPrefix = 'bs-tooltip', trigger = 'hover focus', arrowClassName, - popperClassName, + floatingClassName, innerClassName, ...props }: TooltipProps) { @@ -35,7 +35,7 @@ function Tooltip({ placementPrefix={placementPrefix} trigger={trigger} arrowClassName={classNames('tooltip-arrow', arrowClassName)} - popperClassName={classNames('tooltip', 'show', popperClassName)} + floatingClassName={classNames('tooltip', 'show', floatingClassName)} innerClassName={classNames('tooltip-inner', innerClassName)} /> ); diff --git a/src/TooltipPopoverWrapper.tsx b/src/TooltipPopoverWrapper.tsx index 3c63ce417..ea6cf4b5f 100644 --- a/src/TooltipPopoverWrapper.tsx +++ b/src/TooltipPopoverWrapper.tsx @@ -9,8 +9,13 @@ import { type RefObject, type SyntheticEvent, } from 'react'; -import type { Boundary, Placement, PositioningStrategy } from '@popperjs/core'; -import PopperContent, { type PopperModifier } from './PopperContent'; +import type { + Boundary, + Middleware, + OffsetOptions, + Strategy, +} from '@floating-ui/react-dom'; +import FloatingContent, { type FloatingPlacement } from './FloatingContent'; import { getTarget, mapToCssModules, @@ -35,26 +40,27 @@ export interface TooltipPopoverWrapperProps extends Omit< /** Ignore triggers and `toggle` calls. */ disabled?: boolean; hideArrow?: boolean; - /** `preventOverflow` boundary. */ - boundariesElement?: Boundary | string; - placement?: Placement; + /** Clipping boundary for `shift`. */ + boundary?: Boundary; + placement?: FloatingPlacement; className?: string; innerClassName?: string; arrowClassName?: string; - popperClassName?: string; + floatingClassName?: string; cssModule?: CSSModule; /** Called to open or close the popup. */ toggle?: MouseEventHandler | (() => void); /** Hide when the pointer leaves the target even if it moves onto the popup. */ autohide?: boolean; - /** Adds `${placementPrefix}-auto` to the popper. */ + /** Adds `${placementPrefix}-auto` to the floating element. */ placementPrefix?: string; /** Show/hide delay in ms (default `{ show: 0, hide: 50 }`). */ delay?: TooltipPopoverDelay; - modifiers?: PopperModifier[]; - strategy?: PositioningStrategy; - /** Popper `offset` modifier; falls back to `PopperContent.defaultProps.offset`. */ - offset?: [number, number]; + /** Extra Floating UI middleware; same-named ones replace the defaults. */ + middleware?: Middleware[]; + strategy?: Strategy; + /** Distance from the target; falls back to `FloatingContent.defaultProps.offset`. */ + offset?: OffsetOptions; innerRef?: Ref; /** Space separated: `click`, `hover`, `focus`, `legacy` or `manual`. */ trigger?: string; @@ -78,17 +84,17 @@ const ownKeys = [ 'isOpen', 'disabled', 'hideArrow', - 'boundariesElement', + 'boundary', 'className', 'innerClassName', 'arrowClassName', - 'popperClassName', + 'floatingClassName', 'cssModule', 'toggle', 'autohide', 'placementPrefix', 'delay', - 'modifiers', + 'middleware', 'strategy', 'offset', 'innerRef', @@ -314,13 +320,13 @@ class TooltipPopoverWrapper extends Component< innerClassName, isOpen, hideArrow, - boundariesElement, + boundary, placement, placementPrefix, arrowClassName, - popperClassName, + floatingClassName, container, - modifiers, + middleware, strategy, offset, fade, @@ -329,18 +335,18 @@ class TooltipPopoverWrapper extends Component< } = this.props; return ( - )} - + ); } } diff --git a/src/__mocks__/popper.tsx b/src/__mocks__/popper.tsx deleted file mode 100644 index b7509da30..000000000 --- a/src/__mocks__/popper.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import type { ReactNode } from 'react'; -import type { PopperChildrenProps, PopperProps } from '../popper'; - -const noop = () => {}; - -export function Manager({ children }: { children?: ReactNode }) { - return children; -} - -export const Popper = vi.fn(({ children, placement = 'bottom' }: PopperProps) => - children({ - ref: noop, - placement, - style: {}, - isReferenceHidden: false, - hasPopperEscaped: false, - update: noop, - forceUpdate: noop, - arrowProps: { ref: noop, style: {} }, - } satisfies PopperChildrenProps), -); - -export function Reference({ - children, -}: { - children: (a: { ref: typeof noop }) => ReactNode; -}) { - return children({ ref: noop }); -} diff --git a/src/__tests__/ButtonDropdown.spec.tsx b/src/__tests__/ButtonDropdown.spec.tsx index 690282118..17c7ebc69 100644 --- a/src/__tests__/ButtonDropdown.spec.tsx +++ b/src/__tests__/ButtonDropdown.spec.tsx @@ -1,8 +1,6 @@ import { render, screen } from '@testing-library/react'; import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from '..'; -vi.mock('../popper'); - describe('ButtonDropdown', () => { const toggle = () => {}; diff --git a/src/__tests__/Dropdown.spec.tsx b/src/__tests__/Dropdown.spec.tsx index e0a4890f4..b1aab8c4e 100644 --- a/src/__tests__/Dropdown.spec.tsx +++ b/src/__tests__/Dropdown.spec.tsx @@ -11,8 +11,6 @@ import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from '..'; import { keyCodes } from '../utils'; import { testForChildrenInComponent } from '../testUtils'; -vi.mock('../popper'); - describe('Dropdown', () => { let user: ReturnType; @@ -1116,7 +1114,7 @@ describe('Dropdown', () => { }); describe('Dropdown in navbar', () => { - it('should open without popper with inNavbar prop', async () => { + it('should open statically with inNavbar prop', async () => { render( diff --git a/src/__tests__/DropdownMenu.spec.tsx b/src/__tests__/DropdownMenu.spec.tsx index 82ef83ff3..93f7674e5 100644 --- a/src/__tests__/DropdownMenu.spec.tsx +++ b/src/__tests__/DropdownMenu.spec.tsx @@ -1,12 +1,8 @@ import { screen } from '@testing-library/react'; -import { Popper } from '../popper'; +import { useFloating } from '@floating-ui/react-dom'; import type { DropdownContextValue } from '../DropdownContext'; import { DropdownMenu } from '..'; -import { customDropdownRender } from '../testUtils'; - -vi.mock('../popper'); - -const PopperMock = vi.mocked(Popper); +import { customDropdownRender, lastFloating, middleware } from '../testUtils'; describe('DropdownMenu', () => { const contextProps = { @@ -68,7 +64,7 @@ describe('DropdownMenu', () => { expect(screen.getByText(/ello world/i)).not.toHaveClass( 'dropdown-menu-end', ); - expect(PopperMock.mock.calls[0][0].placement).toBe('bottom-start'); + expect(lastFloating().placement).toBe('bottom-start'); }); it('should render down when direction is unknown on the context', async () => { @@ -100,7 +96,6 @@ describe('DropdownMenu', () => { 'data-popper-placement', 'top-start', ); - // expect(wrapper.find(Popper).prop('placement')).toBe('top-start'); }); it('should render left when direction is "start" on the context', async () => { @@ -111,7 +106,6 @@ describe('DropdownMenu', () => { 'data-popper-placement', 'left-start', ); - // expect(wrapper.find(Popper).prop('placement')).toBe('left-start'); }); it('should render right when direction is "end" on the context', async () => { @@ -122,31 +116,63 @@ describe('DropdownMenu', () => { 'data-popper-placement', 'right-start', ); - // expect(wrapper.find(Popper).prop('placement')).toBe('right-start'); }); - it('should not disable flip modifier by default', async () => { + it('should flip and shift by default', async () => { contextProps.isOpen = true; customDropdownRender(Ello world, contextProps); - expect(PopperMock.mock.calls[0][0].modifiers![0]).toMatchObject({ - name: 'flip', - enabled: true, - }); + expect(middleware('flip')).toBeDefined(); + expect(middleware('shift')).toBeDefined(); }); - it('should disable flip modifier when flip is false', async () => { + it('should not flip when flip is false', async () => { contextProps.isOpen = true; customDropdownRender( Ello world, contextProps, ); - expect(PopperMock.mock.calls.length).toBe(1); - expect(PopperMock.mock.calls[0][0].modifiers![0]).toMatchObject({ - name: 'flip', - enabled: false, + expect(middleware('flip')).toBeUndefined(); + expect(middleware('shift')).toBeDefined(); + }); + + it('should let custom middleware replace same-named defaults', async () => { + contextProps.isOpen = true; + const custom = { name: 'shift', fn: (s: { x: number; y: number }) => s }; + customDropdownRender( + Ello world, + contextProps, + ); + + const names = lastFloating().middleware?.map((m) => m && m.name); + expect(names).toEqual(['flip', 'shift']); + expect(lastFloating().middleware).toContain(custom); + }); + + it('should float against the toggle from context', async () => { + contextProps.isOpen = true; + const reference = document.createElement('button'); + customDropdownRender(Ello world, { + ...contextProps, + reference, }); + + expect(lastFloating().elements?.reference).toBe(reference); + }); + + it('should keep a custom onClick and reposition with updateOnSelect', async () => { + contextProps.isOpen = true; + const onClick = vi.fn(); + customDropdownRender( + + Ello world + , + contextProps, + ); + + screen.getByText(/ello world/i).click(); + expect(onClick).toHaveBeenCalledTimes(1); }); it('should position using fixed mode', async () => { @@ -155,16 +181,16 @@ describe('DropdownMenu', () => { Ello world, contextProps, ); - expect(PopperMock.mock.calls[0][0].strategy).toBe('fixed'); + expect(lastFloating().strategy).toBe('fixed'); }); - it('should not render Popper when isOpen is false', async () => { + it('should not position the menu when isOpen is false', async () => { customDropdownRender( Ello world, contextProps, ); - expect(PopperMock).not.toHaveBeenCalled(); + expect(useFloating).not.toHaveBeenCalled(); }); it('should render custom tag', async () => { diff --git a/src/__tests__/DropdownToggle.spec.tsx b/src/__tests__/DropdownToggle.spec.tsx index f577f55e6..c06bff679 100644 --- a/src/__tests__/DropdownToggle.spec.tsx +++ b/src/__tests__/DropdownToggle.spec.tsx @@ -4,8 +4,6 @@ import type { DropdownContextValue } from '../DropdownContext'; import { DropdownToggle } from '..'; import { customDropdownRender } from '../testUtils'; -vi.mock('../popper'); - describe('DropdownToggle', () => { const user = userEvent.setup(); const contextProps = { diff --git a/src/__tests__/PopperContent.spec.tsx b/src/__tests__/FloatingContent.spec.tsx similarity index 50% rename from src/__tests__/PopperContent.spec.tsx rename to src/__tests__/FloatingContent.spec.tsx index f86eed9b1..ebee3ff8b 100644 --- a/src/__tests__/PopperContent.spec.tsx +++ b/src/__tests__/FloatingContent.spec.tsx @@ -1,10 +1,8 @@ import { render, screen } from '@testing-library/react'; -import { Popper } from '../popper'; -import { PopperContent } from '..'; +import { FloatingContent } from '..'; +import { lastFloating, middleware } from '../testUtils'; -vi.mock('../popper'); - -describe('PopperContent', () => { +describe('FloatingContent', () => { let element: HTMLDivElement; beforeEach(() => { @@ -23,16 +21,16 @@ describe('PopperContent', () => { }); it('should NOT render children when isOpen is false', () => { - render(Yo!); + render(Yo!); expect(screen.queryByText('Yo!')).not.toBeInTheDocument(); }); it('should render children when isOpen is true and container is inline', () => { render( - + Yo! - , + , ); expect(screen.queryByText('Yo!')).toBeInTheDocument(); @@ -42,32 +40,32 @@ describe('PopperContent', () => { const targetElement = element.querySelector('#target')!; render( - + Yo! - , + , ); expect(screen.queryByText('Yo!')).toBeInTheDocument(); }); - it('should render an Arrow in the Popper when isOpen is true and container is inline', () => { + it('should render an arrow when isOpen is true and container is inline', () => { const { container } = render( - Yo! - , + , ); expect(container.querySelector('.arrow.custom-arrow')).toBeInTheDocument(); }); - it('should NOT render an Arrow in the Popper when "hideArrow" is truthy', () => { + it('should NOT render an arrow when "hideArrow" is truthy', () => { const { container } = render( - { hideArrow > Yo! - , + , ); expect( @@ -83,9 +81,9 @@ describe('PopperContent', () => { ).not.toBeInTheDocument(); }); - it('should pass additional classNames to the popper', () => { + it('should pass additional classNames to the wrapper', () => { render( - { data-testid="rick" > Yo! - , + , ); expect(screen.getByTestId('rick')).toHaveClass('extra'); }); - it('should allow custom modifiers and even allow overriding of default modifiers', () => { + it('should allow custom middleware and let it replace same-named defaults', () => { + const shift = { name: 'shift', fn: (st: { x: number; y: number }) => st }; + const custom = { name: 'custom', fn: (st: { x: number; y: number }) => st }; render( - Yo! - , + , ); - expect(vi.mocked(Popper).mock.calls[0][0]).toEqual( - expect.objectContaining({ - modifiers: expect.arrayContaining([ - expect.objectContaining({ - name: 'offset', - options: { - offset: [2, 2], - }, - }), - expect.objectContaining({ - name: 'preventOverflow', - options: { - boundary: 'viewport', - }, - }), - ]), - }), + expect(lastFloating().middleware?.map((m) => m && m.name)).toEqual([ + 'offset', + 'flip', + 'shift', + 'custom', + 'arrow', + ]); + expect(lastFloating().middleware).toContain(shift); + }); + + it('should use autoPlacement instead of flip for auto placements', () => { + render( + + Yo! + , ); + + expect(lastFloating().placement).toBeUndefined(); + expect(middleware('autoPlacement')?.options).toEqual({ + alignment: 'start', + }); + expect(middleware('flip')).toBeUndefined(); + }); + + it('should not flip when flip is false', () => { + render( + + Yo! + , + ); + + expect(middleware('flip')).toBeUndefined(); + }); + + it('should pass fallbackPlacements, boundary and strategy', () => { + const boundary = document.createElement('div'); + render( + + Yo! + , + ); + + expect(middleware('flip')?.options).toEqual({ + fallbackPlacements: ['bottom'], + }); + expect(middleware('shift')?.options).toEqual({ boundary }); + expect(lastFloating().strategy).toBe('fixed'); }); it('should have data-popper-placement of auto by default', () => { const { container } = render( - + Yo! - , + , ); expect( @@ -159,9 +195,14 @@ describe('PopperContent', () => { it('should override data-popper-placement', () => { const { container } = render( - + Yo! - , + , ); expect( @@ -175,14 +216,14 @@ describe('PopperContent', () => { it('should allow for a placement prefix', () => { render( - Yo! - , + , ); expect(screen.getByText('Yo!')).toHaveClass('dropdown-auto'); @@ -190,7 +231,7 @@ describe('PopperContent', () => { it('should allow for a placement prefix with custom placement', () => { const { container } = render( - { container="inline" > Yo! - , + , ); expect(screen.getByText('Yo!')).toHaveClass('dropdown-auto'); @@ -207,9 +248,9 @@ describe('PopperContent', () => { ).toBeInTheDocument(); }); - it('should render custom tag for the popper', () => { + it('should render custom tag for the wrapper', () => { render( - { data-testid="morty" > Yo! - , + , ); expect(screen.getByTestId('morty').tagName.toLowerCase()).toBe('main'); @@ -226,72 +267,64 @@ describe('PopperContent', () => { it('should allow a function to be used as children', () => { const renderChildren = vi.fn(); render( - + {renderChildren} - , + , ); expect(renderChildren).toHaveBeenCalled(); }); it('should render children properly when children is a function', () => { render( - + {() => 'Yo!'} - , + , ); expect(screen.queryByText('Yo!')).toBeInTheDocument(); }); describe('defaultProps', () => { - const modifiers = () => vi.mocked(Popper).mock.calls.at(-1)![0].modifiers; - - it('should default offset to [0, 0]', () => { + it('should default offset to 0', () => { render( - + Yo! - , + , ); - expect(modifiers()).toContainEqual({ - name: 'offset', - options: { offset: [0, 0] }, - }); + expect(middleware('offset')?.options).toEqual(0); }); - it('should honor a patched PopperContent.defaultProps.offset', () => { - const original = PopperContent.defaultProps.offset; - PopperContent.defaultProps.offset = [0, 5]; + it('should honor a patched FloatingContent.defaultProps.offset', () => { + const original = FloatingContent.defaultProps.offset; + FloatingContent.defaultProps.offset = 5; try { render( - + Yo! - , + , ); - expect(modifiers()).toContainEqual({ - name: 'offset', - options: { offset: [0, 5] }, - }); + expect(middleware('offset')?.options).toEqual(5); } finally { - PopperContent.defaultProps.offset = original; + FloatingContent.defaultProps.offset = original; } }); it('should let an explicit offset win over defaultProps', () => { render( - Yo! - , + , ); - expect(modifiers()).toContainEqual({ - name: 'offset', - options: { offset: [3, 4] }, + expect(middleware('offset')?.options).toEqual({ + mainAxis: 4, + crossAxis: 3, }); }); }); diff --git a/src/__tests__/Popover.spec.tsx b/src/__tests__/Popover.spec.tsx index 9b6fe89b1..c68f1945e 100644 --- a/src/__tests__/Popover.spec.tsx +++ b/src/__tests__/Popover.spec.tsx @@ -1,12 +1,8 @@ import { render, screen } from '@testing-library/react'; -import { Popper } from '../popper'; -import PopperContent from '../PopperContent'; +import { lastFloating, middleware } from '../testUtils'; +import FloatingContent from '../FloatingContent'; import Popover from '../Popover'; -vi.mock('../popper'); - -const lastPopperProps = () => vi.mocked(Popper).mock.calls.at(-1)![0]; - describe('Popover', () => { let element: HTMLDivElement; beforeEach(() => { @@ -19,9 +15,9 @@ describe('Popover', () => { document.body.removeChild(element); }); - it('should apply popperClassName to popper component', () => { + it('should apply floatingClassName to the floating element', () => { render( - + Bo-Katan Kryze , ); @@ -43,47 +39,45 @@ describe('Popover', () => { // Regression: React 19 ignores defaultProps on function components. describe('defaults', () => { - it('should pass offset [0, 8] to popper', () => { + it('should default offset to 8', () => { render( Content , ); - expect(lastPopperProps().modifiers).toContainEqual({ - name: 'offset', - options: { offset: [0, 8] }, - }); + expect(middleware('offset')?.options).toEqual(8); }); it('should let an explicit offset win', () => { render( - + Content , ); - expect(lastPopperProps().modifiers).toContainEqual({ - name: 'offset', - options: { offset: [1, 2] }, + expect(middleware('offset')?.options).toEqual({ + mainAxis: 2, + crossAxis: 1, }); }); - it('should keep offset [0, 8] when PopperContent.defaultProps.offset is patched', () => { - const original = PopperContent.defaultProps.offset; - PopperContent.defaultProps.offset = [0, 5]; + it('should keep offset 8 when FloatingContent.defaultProps.offset is patched', () => { + const original = FloatingContent.defaultProps.offset; + FloatingContent.defaultProps.offset = 5; try { render( Content , ); - expect(lastPopperProps().modifiers).toContainEqual({ - name: 'offset', - options: { offset: [0, 8] }, - }); + expect(middleware('offset')?.options).toEqual(8); } finally { - PopperContent.defaultProps.offset = original; + FloatingContent.defaultProps.offset = original; } }); @@ -94,7 +88,7 @@ describe('Popover', () => { , ); - expect(lastPopperProps().placement).toBe('right'); + expect(lastFloating().placement).toBe('right'); expect(screen.getByText('Content').parentElement).toHaveClass( 'bs-popover-auto', ); diff --git a/src/__tests__/Tooltip.spec.tsx b/src/__tests__/Tooltip.spec.tsx index 5cf1ecd38..46f4c7a95 100644 --- a/src/__tests__/Tooltip.spec.tsx +++ b/src/__tests__/Tooltip.spec.tsx @@ -1,12 +1,8 @@ import { act, fireEvent, render, screen } from '@testing-library/react'; -import { Popper } from '../popper'; -import PopperContent from '../PopperContent'; +import { lastFloating, middleware } from '../testUtils'; +import FloatingContent from '../FloatingContent'; import Tooltip from '../Tooltip'; -vi.mock('../popper'); - -const lastPopperProps = () => vi.mocked(Popper).mock.calls.at(-1)![0]; - describe('Tooltip', () => { let element: HTMLDivElement; beforeEach(() => { @@ -19,9 +15,9 @@ describe('Tooltip', () => { document.body.removeChild(element); }); - it('should apply popperClassName to popper component', () => { + it('should apply floatingClassName to the floating element', () => { render( - + Bo-Katan Kryze , ); @@ -57,7 +53,7 @@ describe('Tooltip', () => { , ); - expect(lastPopperProps().placement).toBe('top'); + expect(lastFloating().placement).toBe('top'); expect(screen.getByText('Content').parentElement).toHaveClass( 'bs-tooltip-auto', ); @@ -97,34 +93,30 @@ describe('Tooltip', () => { expect(toggle).toHaveBeenCalledTimes(1); }); - it('should use the PopperContent default offset', () => { + it('should use the FloatingContent default offset', () => { render( Content , ); - expect(lastPopperProps().modifiers).toContainEqual({ - name: 'offset', - options: { offset: PopperContent.defaultProps.offset }, - }); + expect(middleware('offset')?.options).toEqual( + FloatingContent.defaultProps.offset, + ); }); - it('should honor a patched PopperContent.defaultProps.offset', () => { - const original = PopperContent.defaultProps.offset; - PopperContent.defaultProps.offset = [0, 5]; + it('should honor a patched FloatingContent.defaultProps.offset', () => { + const original = FloatingContent.defaultProps.offset; + FloatingContent.defaultProps.offset = 5; try { render( Content , ); - expect(lastPopperProps().modifiers).toContainEqual({ - name: 'offset', - options: { offset: [0, 5] }, - }); + expect(middleware('offset')?.options).toEqual(5); } finally { - PopperContent.defaultProps.offset = original; + FloatingContent.defaultProps.offset = original; } }); }); diff --git a/src/__tests__/TooltipPopoverWrapper.spec.tsx b/src/__tests__/TooltipPopoverWrapper.spec.tsx index 7e6c69907..fd5b89dd3 100644 --- a/src/__tests__/TooltipPopoverWrapper.spec.tsx +++ b/src/__tests__/TooltipPopoverWrapper.spec.tsx @@ -1,11 +1,9 @@ import { act, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { createRef } from 'react'; -import { Popper } from '../popper'; +import { lastFloating } from '../testUtils'; import TooltipPopoverWrapper from '../TooltipPopoverWrapper'; -vi.mock('../popper'); - describe('Tooltip', () => { let element: HTMLDivElement; let container: HTMLDivElement; @@ -219,67 +217,42 @@ describe('Tooltip', () => { // TODO: RTL currently doesn't support touch events }); - it('should pass down custom modifiers', async () => { + it('should pass down custom middleware, replacing same-named defaults', async () => { + const offset = { name: 'offset', fn: (s: { x: number; y: number }) => s }; + const custom = { name: 'custom', fn: (s: { x: number; y: number }) => s }; render( Tooltip Content , ); - expect(vi.mocked(Popper).mock.calls[0][0].modifiers).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - name: 'offset', - options: { - offset: [2, 2], - }, - }), - ]), - ); - - expect(vi.mocked(Popper).mock.calls[0][0].modifiers).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - name: 'preventOverflow', - options: { - boundary: 'viewport', - }, - }), - ]), + const mw = lastFloating().middleware!; + expect(mw.filter((m) => m && m.name === 'offset')).toEqual([offset]); + expect(mw).toContain(custom); + expect(mw.map((m) => m && m.name)).toEqual( + expect.arrayContaining(['flip', 'shift']), ); }); - describe('PopperContent', () => { - const PopperContent = vi.fn((props: any) => + describe('FloatingContent', () => { + const FloatingContent = vi.fn((props: any) => props.children({ update: () => {} }), ); let Wrapper: typeof TooltipPopoverWrapper; beforeEach(async () => { vi.resetModules(); - vi.doMock('../PopperContent', () => ({ default: PopperContent })); + vi.doMock('../FloatingContent', () => ({ default: FloatingContent })); Wrapper = (await import('../TooltipPopoverWrapper')).default; }); afterEach(() => { - vi.doUnmock('../PopperContent'); + vi.doUnmock('../FloatingContent'); }); it('should pass down cssModule', async () => { @@ -293,9 +266,9 @@ describe('Tooltip', () => { , ); - expect(PopperContent).toHaveBeenCalledTimes(1); + expect(FloatingContent).toHaveBeenCalledTimes(1); - expect(PopperContent.mock.calls[0][0]).toEqual( + expect(FloatingContent.mock.calls[0][0]).toEqual( expect.objectContaining({ cssModule: expect.objectContaining({ a: 'b', @@ -306,15 +279,13 @@ describe('Tooltip', () => { it('should pass down offset', async () => { render( - + Tooltip content , ); - expect(PopperContent).toHaveBeenCalledTimes(1); - expect(PopperContent.mock.calls[0][0].offset).toEqual( - expect.arrayContaining([0, 12]), - ); + expect(FloatingContent).toHaveBeenCalledTimes(1); + expect(FloatingContent.mock.calls[0][0].offset).toBe(12); }); it('should not inject an offset when none is passed', async () => { @@ -324,8 +295,8 @@ describe('Tooltip', () => { , ); - expect(PopperContent).toHaveBeenCalledTimes(1); - expect(PopperContent.mock.calls[0][0].offset).toBeUndefined(); + expect(FloatingContent).toHaveBeenCalledTimes(1); + expect(FloatingContent.mock.calls[0][0].offset).toBeUndefined(); }); it('should pass down flip', async () => { @@ -335,8 +306,8 @@ describe('Tooltip', () => { , ); - expect(PopperContent).toHaveBeenCalledTimes(1); - expect(PopperContent.mock.calls[0][0].flip).toBe(false); + expect(FloatingContent).toHaveBeenCalledTimes(1); + expect(FloatingContent.mock.calls[0][0].flip).toBe(false); }); it('should handle inner target click and correct placement', async () => { @@ -358,7 +329,7 @@ describe('Tooltip', () => { , ); - expect(PopperContent.mock.calls[0][0].target.id).toBe('target'); + expect(FloatingContent.mock.calls[0][0].target.id).toBe('target'); }); }); diff --git a/src/__tests__/Uncontrolled.spec.tsx b/src/__tests__/Uncontrolled.spec.tsx index 9ccf056f4..9a1ca94a4 100644 --- a/src/__tests__/Uncontrolled.spec.tsx +++ b/src/__tests__/Uncontrolled.spec.tsx @@ -15,8 +15,6 @@ import { } from '..'; import { testForDefaultClass } from '../testUtils'; -vi.mock('../popper'); - let user: ReturnType; beforeEach(() => { diff --git a/src/__tests__/polymorphic.popper.tsx b/src/__tests__/polymorphic.floating.tsx similarity index 88% rename from src/__tests__/polymorphic.popper.tsx rename to src/__tests__/polymorphic.floating.tsx index 4e619886d..16454e589 100644 --- a/src/__tests__/polymorphic.popper.tsx +++ b/src/__tests__/polymorphic.floating.tsx @@ -1,4 +1,4 @@ -// Compile-only: polymorphic `tag` typing (popper, dropdown, carousel groups). +// Compile-only: polymorphic `tag` typing (floating, dropdown, carousel groups). import type { ReactNode } from 'react'; import { ButtonDropdown, @@ -9,7 +9,7 @@ import { DropdownToggle, PopoverBody, PopoverHeader, - PopperContent, + FloatingContent, UncontrolledButtonDropdown, UncontrolledDropdown, type PopoverProps, @@ -45,12 +45,12 @@ export const ok = ( - + x - - + + x - + void el} /> ); @@ -78,9 +78,9 @@ export const bad = ( {/* @ts-expect-error unknown prop */} {/* @ts-expect-error typo on Link prop */} - + x - + ); @@ -95,8 +95,8 @@ export const badStringTag = ( {/* @ts-expect-error typo on DOM prop */} {}} /> {/* @ts-expect-error typo on DOM prop */} - {}}> + {}}> x - + ); diff --git a/src/__tests__/setup.ts b/src/__tests__/setup.ts index bb8bb02ff..619aad76e 100644 --- a/src/__tests__/setup.ts +++ b/src/__tests__/setup.ts @@ -8,4 +8,10 @@ Object.assign(globalThis, { jest: { advanceTimersByTime: (ms: number) => vi.advanceTimersByTime(ms) }, }); +// Real implementation, spied so specs can assert positioning options (see `lastFloating`). +vi.mock('@floating-ui/react-dom', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useFloating: vi.fn(mod.useFloating) }; +}); + afterEach(() => cleanup()); diff --git a/src/__tests__/typings.tsx b/src/__tests__/typings.tsx index 7097e4a70..5fdb39d32 100644 --- a/src/__tests__/typings.tsx +++ b/src/__tests__/typings.tsx @@ -4268,7 +4268,7 @@ function Example() { Hello world! @@ -4975,7 +4975,7 @@ function Example126() { Popover Title Lorem ipsum dolor sit amet diff --git a/src/index.ts b/src/index.ts index 064fa6d5b..edadec5c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -102,9 +102,10 @@ export { export { default as CardText, type CardTextProps } from './CardText'; export { default as CardTitle, type CardTitleProps } from './CardTitle'; export { - default as PopperContent, - type PopperContentProps, -} from './PopperContent'; + default as FloatingContent, + type FloatingContentProps, + type FloatingPlacement, +} from './FloatingContent'; export { default as Popover, type PopoverProps } from './Popover'; export { default as UncontrolledPopover, diff --git a/src/popper.tsx b/src/popper.tsx deleted file mode 100644 index 5d3aaac0e..000000000 --- a/src/popper.tsx +++ /dev/null @@ -1,206 +0,0 @@ -import { - createContext, - useCallback, - useContext, - useLayoutEffect, - useMemo, - useRef, - useState, - type CSSProperties, - type ReactNode, - type Ref, -} from 'react'; -import { - createPopper, - type Instance, - type Modifier, - type Placement, - type PositioningStrategy, - type State, -} from '@popperjs/core'; - -/** - * Minimal replacement for `react-popper` v2 (React 19 compatible). - * Same `Manager` / `Reference` / `Popper` render-prop API. - */ - -type SetRef = (el: HTMLElement | null) => void; - -const ManagerContext = createContext<{ - reference: Element | null; - setReference: SetRef; -} | null>(null); - -export function Manager({ children }: { children?: ReactNode }) { - const [reference, setReference] = useState(null); - const value = useMemo(() => ({ reference, setReference }), [reference]); - return ( - {children} - ); -} - -function setRef(ref: Ref | undefined, value: T) { - if (typeof ref === 'function') ref(value); - else if (ref) ref.current = value; -} - -export function Reference({ - children, - innerRef, -}: { - children: (args: { ref: SetRef }) => ReactNode; - innerRef?: Ref; -}) { - const setReference = useContext(ManagerContext)?.setReference; - const ref = useCallback( - (el: HTMLElement | null) => { - setRef(innerRef, el); - setReference?.(el); - }, - [innerRef, setReference], - ); - return children({ ref }); -} - -const plain = (v: unknown): v is Record => - !!v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype; - -function deepEqual(a: unknown, b: unknown): boolean { - if (a === b) return true; - if (Array.isArray(a) && Array.isArray(b)) { - return a.length === b.length && a.every((v, i) => deepEqual(v, b[i])); - } - if (plain(a) && plain(b)) { - const keys = Object.keys(a); - return ( - keys.length === Object.keys(b).length && - keys.every((k) => deepEqual(a[k], b[k])) - ); - } - return false; -} - -export interface PopperChildrenProps { - ref: SetRef; - style: CSSProperties; - placement: Placement; - isReferenceHidden: boolean; - hasPopperEscaped: boolean; - update: () => Promise> | void; - forceUpdate: () => void; - arrowProps: { ref: SetRef; style: CSSProperties }; -} - -export interface PopperProps { - children: (props: PopperChildrenProps) => ReactNode; - referenceElement?: Element | null; - placement?: Placement; - strategy?: PositioningStrategy; - modifiers?: Partial>[]; - innerRef?: Ref; - onFirstUpdate?: (state: Partial) => void; -} - -type PopperState = Pick & { - styles: { popper: CSSProperties; arrow: CSSProperties }; - attributes: State['attributes']; -}; - -export function Popper({ - children, - referenceElement, - placement = 'bottom', - strategy = 'absolute', - modifiers = [], - innerRef, - onFirstUpdate, -}: PopperProps) { - const managerReference = useContext(ManagerContext)?.reference ?? null; - const reference = referenceElement ?? managerReference; - const [popperElement, setPopperElement] = useState(null); - const [arrowElement, setArrowElement] = useState(null); - const [state, setState] = useState({ - placement, - styles: { - popper: { position: strategy, left: '0', top: '0' }, - arrow: { position: 'absolute' }, - }, - attributes: {}, - }); - - const popperRef = useCallback( - (el: HTMLElement | null) => { - setRef(innerRef, el); - setPopperElement(el); - }, - [innerRef], - ); - - const updateState = useMemo( - () => ({ - name: 'updateState', - enabled: true, - phase: 'write' as const, - fn: ({ state: s }: { state: State }) => - setState({ - placement: s.placement, - styles: { - popper: (s.styles.popper ?? {}) as CSSProperties, - arrow: (s.styles.arrow ?? {}) as CSSProperties, - }, - attributes: s.attributes, - }), - requires: ['computeStyles'], - }), - [], - ); - - const nextOptions = { - onFirstUpdate, - placement, - strategy, - modifiers: [ - ...modifiers, - { - name: 'arrow', - enabled: !!arrowElement, - options: { element: arrowElement }, - }, - updateState, - { name: 'applyStyles', enabled: false }, - ], - }; - // Stable identity while deep-equal, so popper isn't recreated every render. - const [options, setOptions] = useState(nextOptions); - if (!deepEqual(options, nextOptions)) setOptions(nextOptions); - - const instance = useRef(null); - - useLayoutEffect(() => { - if (!reference || !popperElement) return; - const popper = createPopper(reference, popperElement, options as never); - instance.current = popper; - return () => { - popper.destroy(); - instance.current = null; - }; - }, [reference, popperElement, options]); - - const update = useCallback(() => instance.current?.update(), []); - const forceUpdate = useCallback(() => instance.current?.forceUpdate(), []); - - const popperAttrs = state.attributes.popper ?? {}; - - // `update`/`forceUpdate` read the ref only when invoked, never during render. - // oxlint-disable-next-line react/refs - return children({ - ref: popperRef, - style: state.styles.popper, - placement: state.placement, - isReferenceHidden: !!popperAttrs['data-popper-reference-hidden'], - hasPopperEscaped: !!popperAttrs['data-popper-escaped'], - update, - forceUpdate, - arrowProps: { ref: setArrowElement, style: state.styles.arrow }, - }); -} diff --git a/src/testUtils.tsx b/src/testUtils.tsx index 1ae905f65..35e5976bc 100644 --- a/src/testUtils.tsx +++ b/src/testUtils.tsx @@ -1,5 +1,6 @@ import type { ComponentType, ReactNode } from 'react'; import { render, screen } from '@testing-library/react'; +import { useFloating } from '@floating-ui/react-dom'; import { DropdownContext, type DropdownContextValue } from './DropdownContext'; type AnyComponent = ComponentType; @@ -56,3 +57,13 @@ export const customDropdownRender = ( {ui} , ); + +/** Options of the last `useFloating` call (spied in `__tests__/setup.ts`). */ +export const lastFloating = () => + vi.mocked(useFloating).mock.calls.at(-1)?.[0] ?? {}; + +/** The named middleware of the last `useFloating` call, with its options. */ +export function middleware(name: string) { + const m = lastFloating().middleware?.find((x) => x && x.name === name); + return m ? { options: (m.options as [unknown])[0] } : undefined; +} diff --git a/src/utils.ts b/src/utils.ts index f63606bfd..1ed998d28 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -188,24 +188,6 @@ export const keyCodes = { p: 80, } as const; -export const PopperPlacements = [ - 'auto-start', - 'auto', - 'auto-end', - 'top-start', - 'top', - 'top-end', - 'right-start', - 'right', - 'right-end', - 'bottom-end', - 'bottom', - 'bottom-start', - 'left-end', - 'left', - 'left-start', -] as const; - export const canUseDOM = typeof window !== 'undefined' && !!window.document?.createElement; diff --git a/stories/Upgrading.mdx b/stories/Upgrading.mdx index dc7980252..f12048f3f 100644 --- a/stories/Upgrading.mdx +++ b/stories/Upgrading.mdx @@ -25,8 +25,8 @@ Please see the Bootstrap [Migration Guide](https://getbootstrap.com/docs/5.3/mig ### Components with breaking changes: - Tooltip/Popover/DropdownMenu - - The `modifiers` prop will now conform to the new popper2 modifiers, which take an array instead of an object. - `offset` prop is now an array of 2 numbers that represent skidding and distance. See [popper docs](https://popper.js.org/docs/v2/modifiers/) for more details. + Since v11, positioning uses [Floating UI](https://floating-ui.com/): `modifiers` is replaced by `middleware` + and `offset` takes Floating UI [`OffsetOptions`](https://floating-ui.com/docs/offset). - ModalHeader/ToastHeader - Bootstrap 5 no longer supports custom close icons, so this feature was removed from ModalHeader and ToastHeader. - Dropdown/DropdownMenu - diff --git a/tsconfig.build.json b/tsconfig.build.json index e4d5ef70a..4229544ec 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -11,5 +11,5 @@ "paths": {} }, "include": ["src"], - "exclude": ["src/__tests__", "src/__mocks__", "src/testUtils.tsx"] + "exclude": ["src/__tests__", "src/testUtils.tsx"] } diff --git a/v10-migration.md b/v10-migration.md index 731c62ef7..cf024b2cb 100644 --- a/v10-migration.md +++ b/v10-migration.md @@ -1,5 +1,7 @@ # v10 migration report +> v11 replaced `@popperjs/core` with Floating UI; `PopperContent` is now `FloatingContent`. See CHANGELOG 11.0.0. + `reactstrap@9.2.3` → `@conventioncatcorp/reactstrap@10.0.0`: a TypeScript, React 19 and Bootstrap 5 renovation of the fork. Branch: `v10`. diff --git a/vite.config.ts b/vite.config.ts index f8d3c9b31..0f3970133 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -30,7 +30,7 @@ export default defineConfig({ coverage: { reporter: ['text', 'lcov'], include: ['src/**'], - exclude: ['src/__tests__/**', 'src/__mocks__/**', 'src/testUtils.tsx'], + exclude: ['src/__tests__/**', 'src/testUtils.tsx'], }, }, }); From 0390eb607016d1d58bb55204eec9c345a27ad2d8 Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Wed, 11 Nov 2026 20:39:48 -0800 Subject: [PATCH 3/3] fix: middleware order, shift tether, innerRef swap (review) - Same-named user middleware replaces the default in its slot (a custom `offset` now runs before flip/shift); falsy entries are skipped. - `shift` uses `limitShift()`, matching Popper's `preventOverflow` tether. - `auto-start`/`auto-end` keep their alignment (`autoAlignment: false`). - DropdownToggle re-applies a swapped `innerRef`. - Tests for order, tether, arrow positioning, updateOnSelect, toggle reference and innerRef; CHANGELOG gaps filled. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++++-- src/DropdownMenu.tsx | 27 ++++++----- src/DropdownToggle.tsx | 20 ++++++-- src/FloatingContent.tsx | 64 ++++++++++++++++++-------- src/TooltipPopoverWrapper.tsx | 16 +++---- src/__tests__/Dropdown.spec.tsx | 38 ++++++++++++++- src/__tests__/DropdownMenu.spec.tsx | 40 ++++++++++++---- src/__tests__/FloatingContent.spec.tsx | 64 ++++++++++++++++++++++++-- src/index.ts | 1 + 9 files changed, 226 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 780b54dbd..8d222627b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,20 @@ Positioning moves from `@popperjs/core` (unmaintained since 2023) to [Floating U - `PopperContent` → `FloatingContent` (`PopperContentProps` → `FloatingContentProps`). Patch defaults with `FloatingContent.defaultProps.offset = 5`. - `popperClassName` → `floatingClassName` (Tooltip, Popover, FloatingContent). -- `modifiers` → `middleware` (Floating UI `Middleware[]`; same-named entries replace the defaults `offset`, `flip`, - `shift`). +- `modifiers` → `middleware` (Floating UI middleware, run after the defaults; falsy entries are skipped). A + same-named entry replaces that default in place: `offset`, `flip`/`autoPlacement`, `shift`, `arrow` for + Tooltip/Popover/FloatingContent; `offset` (none by default), `flip`, `shift` for DropdownMenu. Popper's + `preventOverflow` is now `shift`. - `offset: [skidding, distance]` → Floating UI `OffsetOptions`: `[0, 8]` becomes `8`, `[x, y]` becomes `{ mainAxis: y, crossAxis: x }`. Popover defaults to `8`. - `boundariesElement` → `boundary` (Floating UI `Boundary`, default `'clippingAncestors'`). -- `placement` / `strategy` use Floating UI types; `auto`, `auto-start` and `auto-end` still work (via `autoPlacement`). +- `placement` / `strategy` use Floating UI types; `auto`, `auto-start` and `auto-end` still work (via `autoPlacement`, + which ignores `flip` and `fallbackPlacements`). +- Repositions on element resizes and layout shifts too (`autoUpdate`), not only scroll and window resize. `shift` keeps + the element tethered to its target, like Popper's `preventOverflow`. - Removed: `data-popper-reference-hidden` attribute, `Util.PopperPlacements`. -- `DropdownToggle` `innerRef` now also works inside a navbar. +- Fixes: `DropdownToggle` `innerRef` now works inside a navbar (and when swapped); a positioned `DropdownMenu` no + longer drops its `onClick`. # 10.0.0 (2026-11-10) diff --git a/src/DropdownMenu.tsx b/src/DropdownMenu.tsx index b24c70a4c..8c451af83 100644 --- a/src/DropdownMenu.tsx +++ b/src/DropdownMenu.tsx @@ -13,12 +13,13 @@ import classNames from 'classnames'; import { autoUpdate, flip as flipMiddleware, + limitShift, shift, useFloating, - type Middleware, type Placement, type Strategy, } from '@floating-ui/react-dom'; +import { mergeMiddleware, type FloatingMiddleware } from './FloatingContent'; import { DropdownContext, type DropdownDirection } from './DropdownContext'; import { getTarget, @@ -37,8 +38,11 @@ export interface DropdownMenuOwnProps { end?: boolean; /** Flips the menu to the opposite side if there is not enough space to fit */ flip?: boolean; - /** Extra Floating UI middleware; same-named ones replace the defaults (`flip`, `shift`). */ - middleware?: Middleware[]; + /** + * Extra Floating UI middleware, run after the defaults (`flip`, `shift`); a same-named one replaces + * that default in place, and a custom `offset` runs first. + */ + middleware?: FloatingMiddleware[]; cssModule?: CSSModule; /** Keep the menu mounted (and positioned) while closed. */ persist?: boolean; @@ -67,7 +71,7 @@ type FloatingMenuProps = HTMLAttributes & { reference: Element | null; placement: Placement; flip: boolean; - middleware: Middleware[]; + middleware: FloatingMiddleware[]; strategy?: Strategy; updateOnSelect?: boolean; onMenuRef?: (el: HTMLElement | null) => void; @@ -86,17 +90,18 @@ function FloatingMenu({ onClick, ...attrs }: FloatingMenuProps) { - const names = new Set(middleware.map((m) => m.name)); const floating = useFloating({ elements: { reference }, placement, strategy, - middleware: [ - ...[flip && flipMiddleware(), shift()].filter( - (m): m is Middleware => !!m && !names.has(m.name), - ), - ...middleware, - ], + middleware: mergeMiddleware( + [ + ['offset', false], + ['flip', flip && flipMiddleware()], + ['shift', shift({ limiter: limitShift() })], + ], + middleware, + ), whileElementsMounted: autoUpdate, }); const { setFloating } = floating.refs; diff --git a/src/DropdownToggle.tsx b/src/DropdownToggle.tsx index c05c2caca..1d63d479f 100644 --- a/src/DropdownToggle.tsx +++ b/src/DropdownToggle.tsx @@ -49,6 +49,11 @@ type DropdownToggleImplProps = DropdownToggleOwnProps & { tag?: ElementType; } & HTMLAttributes; +function setRef(ref: Ref | undefined, value: V) { + if (typeof ref === 'function') ref(value); + else if (ref) ref.current = value; +} + class DropdownToggle extends Component< DropdownToggleProps > { @@ -67,14 +72,21 @@ class DropdownToggle extends Component< this.context.toggle(e); }; - // Stable, so React only calls it on mount/unmount. + private node: HTMLElement | null = null; + + // Stable, so React only calls it on mount/unmount; `innerRef` swaps are handled in componentDidUpdate. handleRef = (el: HTMLElement | null) => { - const { innerRef } = this.props; - if (typeof innerRef === 'function') innerRef(el); - else if (innerRef) innerRef.current = el; + this.node = el; + setRef(this.props.innerRef, el); this.context.onToggleRef?.(el); }; + override componentDidUpdate(prevProps: DropdownToggleProps) { + if (prevProps.innerRef === this.props.innerRef) return; + setRef(prevProps.innerRef, null); + setRef(this.props.innerRef, this.node); + } + getRole() { return this.context.menuRole || (this.props['aria-haspopup'] ?? true); } diff --git a/src/FloatingContent.tsx b/src/FloatingContent.tsx index 5ab556c8d..96e98dfba 100644 --- a/src/FloatingContent.tsx +++ b/src/FloatingContent.tsx @@ -12,6 +12,7 @@ import { autoPlacement, autoUpdate, flip as flipMiddleware, + limitShift, offset as offsetMiddleware, shift, useFloating, @@ -31,6 +32,25 @@ import { } from './utils'; import Fade, { type FadeProps } from './Fade'; +/** Floating UI middleware; falsy entries are skipped (`[cond && hide()]`). */ +export type FloatingMiddleware = Middleware | false | null | undefined; + +/** + * Default `[name, middleware]` slots in order, each replaced in place by a same-named + * user middleware (Floating UI runs middleware in array order); other user middleware follows. + */ +export function mergeMiddleware( + slots: [name: string, middleware: FloatingMiddleware][], + extra: FloatingMiddleware[], +): Middleware[] { + const user = extra.filter((m): m is Middleware => !!m); + const byName = new Map(user.map((m) => [m.name, m])); + const merged = slots + .map(([name, m]) => byName.get(name) ?? m) + .filter((m): m is Middleware => !!m); + return [...merged, ...user.filter((m) => !merged.includes(m))]; +} + /** Floating UI placement, plus `auto*` (best fitting side, via `autoPlacement`). */ export type FloatingPlacement = Placement | 'auto' | `auto-${Alignment}`; @@ -43,7 +63,7 @@ export interface FloatingContentDefaultProps { offset: OffsetOptions; flip: boolean; container: Target; - middleware: Middleware[]; + middleware: FloatingMiddleware[]; onClosed: () => void; fade: boolean; transition: FadeProps; @@ -65,14 +85,17 @@ export interface FloatingContentOwnProps { cssModule?: CSSModule; /** Distance from the target (`offset` middleware). */ offset?: OffsetOptions; - /** Placements to try when `flip`ping. */ + /** Placements to try when `flip`ping (ignored for `auto*` placements). */ fallbackPlacements?: Placement[]; /** Flip to the opposite side when it would overflow. */ flip?: boolean; - /** Extra Floating UI middleware; same-named ones replace the defaults (`offset`, `flip`, `shift`). */ - middleware?: Middleware[]; + /** + * Extra Floating UI middleware, run after the defaults (`offset`, `flip` or `autoPlacement`, + * `shift`, `arrow`); a same-named one replaces that default in place. + */ + middleware?: FloatingMiddleware[]; strategy?: Strategy; - /** Clipping boundary for `shift`. */ + /** Clipping boundary for `shift` (which keeps the element tethered to the target). */ boundary?: Boundary; onClosed?: () => void; /** Animate with Fade. */ @@ -124,14 +147,6 @@ function Floating({ const [arrowElement, setArrowElement] = useState(null); const [side, alignment] = placement.split('-') as [string, Alignment?]; const auto = side === 'auto'; - const names = new Set(middleware.map((m) => m.name)); - const defaults = [ - offsetMiddleware(offset), - auto - ? autoPlacement({ alignment }) - : flip && flipMiddleware({ fallbackPlacements }), - shift({ boundary }), - ].filter((m): m is Middleware => !!m && !names.has(m.name)); const { refs, @@ -144,11 +159,24 @@ function Floating({ elements: { reference }, placement: auto ? undefined : (placement as Placement), strategy, - middleware: [ - ...defaults, - ...middleware, - arrowElement && arrow({ element: arrowElement }), - ], + middleware: mergeMiddleware( + [ + ['offset', offsetMiddleware(offset)], + auto + ? [ + 'autoPlacement', + autoPlacement( + // Like Popper's `auto-start`: keep the requested alignment. + alignment ? { alignment, autoAlignment: false } : undefined, + ), + ] + : ['flip', flip && flipMiddleware({ fallbackPlacements })], + // The limiter keeps it attached to the target (Popper's `tether`). + ['shift', shift({ boundary, limiter: limitShift() })], + ['arrow', arrowElement && arrow({ element: arrowElement })], + ], + middleware, + ), whileElementsMounted: autoUpdate, }); const { setFloating } = refs; diff --git a/src/TooltipPopoverWrapper.tsx b/src/TooltipPopoverWrapper.tsx index ea6cf4b5f..e7713da78 100644 --- a/src/TooltipPopoverWrapper.tsx +++ b/src/TooltipPopoverWrapper.tsx @@ -9,13 +9,11 @@ import { type RefObject, type SyntheticEvent, } from 'react'; -import type { - Boundary, - Middleware, - OffsetOptions, - Strategy, -} from '@floating-ui/react-dom'; -import FloatingContent, { type FloatingPlacement } from './FloatingContent'; +import type { Boundary, OffsetOptions, Strategy } from '@floating-ui/react-dom'; +import FloatingContent, { + type FloatingMiddleware, + type FloatingPlacement, +} from './FloatingContent'; import { getTarget, mapToCssModules, @@ -56,8 +54,8 @@ export interface TooltipPopoverWrapperProps extends Omit< placementPrefix?: string; /** Show/hide delay in ms (default `{ show: 0, hide: 50 }`). */ delay?: TooltipPopoverDelay; - /** Extra Floating UI middleware; same-named ones replace the defaults. */ - middleware?: Middleware[]; + /** Extra Floating UI middleware; see `FloatingContent`. */ + middleware?: FloatingMiddleware[]; strategy?: Strategy; /** Distance from the target; falls back to `FloatingContent.defaultProps.offset`. */ offset?: OffsetOptions; diff --git a/src/__tests__/Dropdown.spec.tsx b/src/__tests__/Dropdown.spec.tsx index b1aab8c4e..c290307ea 100644 --- a/src/__tests__/Dropdown.spec.tsx +++ b/src/__tests__/Dropdown.spec.tsx @@ -1,3 +1,4 @@ +import { createRef } from 'react'; import { act, createEvent, @@ -9,7 +10,7 @@ import userEvent from '@testing-library/user-event'; import type { Mock } from 'vitest'; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from '..'; import { keyCodes } from '../utils'; -import { testForChildrenInComponent } from '../testUtils'; +import { lastFloating, testForChildrenInComponent } from '../testUtils'; describe('Dropdown', () => { let user: ReturnType; @@ -1204,4 +1205,39 @@ describe('Dropdown', () => { expect(screen.getByRole('listbox')).toBeInTheDocument(); }); }); + + describe('floating menu', () => { + it('should float the menu against the toggle', () => { + render( + {}}> + Toggle + Menu + , + ); + + expect(lastFloating().elements?.reference).toBe( + screen.getByText('Toggle'), + ); + }); + + it.each([false, true])( + 'should set and swap the toggle innerRef (inNavbar: %s)', + (inNavbar) => { + const a = createRef(); + const b = createRef(); + const ui = (ref: typeof a) => ( + {}}> + Toggle + Menu + + ); + const { rerender } = render(ui(a)); + expect(a.current).toBe(screen.getByText('Toggle')); + + rerender(ui(b)); + expect(a.current).toBeNull(); + expect(b.current).toBe(screen.getByText('Toggle')); + }, + ); + }); }); diff --git a/src/__tests__/DropdownMenu.spec.tsx b/src/__tests__/DropdownMenu.spec.tsx index 93f7674e5..e7dd43eb9 100644 --- a/src/__tests__/DropdownMenu.spec.tsx +++ b/src/__tests__/DropdownMenu.spec.tsx @@ -1,5 +1,5 @@ import { screen } from '@testing-library/react'; -import { useFloating } from '@floating-ui/react-dom'; +import { offset, useFloating } from '@floating-ui/react-dom'; import type { DropdownContextValue } from '../DropdownContext'; import { DropdownMenu } from '..'; import { customDropdownRender, lastFloating, middleware } from '../testUtils'; @@ -150,6 +150,19 @@ describe('DropdownMenu', () => { expect(lastFloating().middleware).toContain(custom); }); + it('should run a custom offset before flip and shift', async () => { + contextProps.isOpen = true; + const custom = offset(2); + customDropdownRender( + Ello world, + contextProps, + ); + + const mw = lastFloating().middleware!; + expect(mw.map((m) => m && m.name)).toEqual(['offset', 'flip', 'shift']); + expect(mw[0]).toBe(custom); + }); + it('should float against the toggle from context', async () => { contextProps.isOpen = true; const reference = document.createElement('button'); @@ -164,15 +177,26 @@ describe('DropdownMenu', () => { it('should keep a custom onClick and reposition with updateOnSelect', async () => { contextProps.isOpen = true; const onClick = vi.fn(); - customDropdownRender( - - Ello world - , - contextProps, - ); + const update = vi.fn(); + const actual = vi.mocked(useFloating).getMockImplementation()!; + vi.mocked(useFloating).mockImplementation((o) => ({ + ...actual(o), + update, + })); + try { + customDropdownRender( + + Ello world + , + contextProps, + ); + screen.getByText(/ello world/i).click(); + } finally { + vi.mocked(useFloating).mockImplementation(actual); + } - screen.getByText(/ello world/i).click(); expect(onClick).toHaveBeenCalledTimes(1); + expect(update).toHaveBeenCalledTimes(1); }); it('should position using fixed mode', async () => { diff --git a/src/__tests__/FloatingContent.spec.tsx b/src/__tests__/FloatingContent.spec.tsx index ebee3ff8b..2ec6ae075 100644 --- a/src/__tests__/FloatingContent.spec.tsx +++ b/src/__tests__/FloatingContent.spec.tsx @@ -1,4 +1,5 @@ -import { render, screen } from '@testing-library/react'; +import { act, render, screen } from '@testing-library/react'; +import { offset } from '@floating-ui/react-dom'; import { FloatingContent } from '..'; import { lastFloating, middleware } from '../testUtils'; @@ -116,12 +117,68 @@ describe('FloatingContent', () => { 'offset', 'flip', 'shift', - 'custom', 'arrow', + 'custom', ]); expect(lastFloating().middleware).toContain(shift); }); + it('should run a custom offset in the default slot, before flip and shift', () => { + const custom = offset(4); + render( + + Yo! + , + ); + + const mw = lastFloating().middleware!; + expect(mw.map((m) => m && m.name)).toEqual([ + 'offset', + 'flip', + 'shift', + 'arrow', + ]); + expect(mw[0]).toBe(custom); + }); + + it('should tether shift to the target', () => { + render( + + Yo! + , + ); + + expect(middleware('shift')?.options).toMatchObject({ + limiter: { fn: expect.any(Function) }, + }); + }); + + it('should position the arrow and report the computed placement', async () => { + vi.useRealTimers(); + const { container } = render( + + Yo! + , + ); + + const floating = container.querySelector('[data-popper-placement]')!; + expect(floating).toHaveAttribute('data-popper-placement', 'auto'); + await act(async () => {}); + + expect(floating.getAttribute('data-popper-placement')).toMatch( + /^(top|right|bottom|left)$/, + ); + const arrowStyle = (container.querySelector('.arrow') as HTMLElement).style; + expect(arrowStyle.position).toBe('absolute'); + expect(arrowStyle.left || arrowStyle.top).toMatch(/px$/); + }); + it('should use autoPlacement instead of flip for auto placements', () => { render( { expect(lastFloating().placement).toBeUndefined(); expect(middleware('autoPlacement')?.options).toEqual({ alignment: 'start', + autoAlignment: false, }); expect(middleware('flip')).toBeUndefined(); }); @@ -177,7 +235,7 @@ describe('FloatingContent', () => { expect(middleware('flip')?.options).toEqual({ fallbackPlacements: ['bottom'], }); - expect(middleware('shift')?.options).toEqual({ boundary }); + expect(middleware('shift')?.options).toMatchObject({ boundary }); expect(lastFloating().strategy).toBe('fixed'); }); diff --git a/src/index.ts b/src/index.ts index edadec5c9..76c7d4f3a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -104,6 +104,7 @@ export { default as CardTitle, type CardTitleProps } from './CardTitle'; export { default as FloatingContent, type FloatingContentProps, + type FloatingMiddleware, type FloatingPlacement, } from './FloatingContent'; export { default as Popover, type PopoverProps } from './Popover';